Cod sursa(job #2410042)

Utilizator LucaSeriSeritan Luca LucaSeri Data 19 aprilie 2019 17:51:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>

using namespace std;

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("bfs.in", "r", stdin);
		freopen("bfs.out", "w", stdout);
	#endif

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, m, st;
	cin >> n >> m >> st;

	vector< vector< int > > gr(n + 1);
	for(int i = 0; i < m; ++i) {
		int a, b;
		cin >> a >> b;
		gr[a].emplace_back(b);
	}

	const int inf = 1e9;
	vector< int > dist(n + 1, inf);
	queue< int > q;
	dist[st] = 0;
	q.push(st);
	while(q.size()) {
		int node = q.front();
		q.pop();

		for(auto &x : gr[node]) {
			if(dist[node] + 1 < dist[x]) {
				dist[x] = dist[node] + 1;
				q.push(x);
			}
		}
	}

	for(int i = 1; i <= n; ++i) {
		cout << (dist[i] == inf? -1 : dist[i]) << ' ';
	}
	return 0;
}