Cod sursa(job #2340375)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 10 februarie 2019 12:58:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream in("bfs.in");
ofstream out("bfs.out");

const int MAXN = 1e5;
const int MAXM = 1e6;

int n, m, s;
int d[MAXN + 1];
vector<int> g[MAXN + 1];
bool viz[MAXN + 1];

void bfs(int start) {
	d[start] = 0;
	viz[start] = 1;
	int cur = start;
	queue<int> nodes;
	nodes.push(cur);
	while (nodes.size()) {
		cur = nodes.front();
		nodes.pop();
		for (auto x : g[cur]) {
			if (!viz[x]) {
				viz[x] = true;
				nodes.push(x);
				d[x] = d[cur] + 1;
			}
			
		}
	}
}

int main() {
	in >> n >> m >> s;

	for (int i = 1; i <= m; ++ i) {
		int x, y;
		in >> x >> y;
		g[x].push_back(y);
	}

	bfs(s);

	for (int i = 1; i <= n; ++ i) {
		if (d[i] == 0 && i != s) out << -1 << ' ';
		else out << d[i] << ' ';
	}

	return 0;
}