Pagini recente » Cod sursa (job #3130857) | Cod sursa (job #2085318) | Cod sursa (job #2130678) | Cod sursa (job #2810360) | Cod sursa (job #2225691)
#include <bits/stdc++.h>
using namespace std;
int distance[1000001];
vector <int> graph[100001];
int main() {
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
int n, m, source;
fin >> n >> m >> source;
for (int i = 1; i <= n; ++i) {
distance[i] = 1000000000;
}
distance[source] = 0;
for (int i = 1; i <= m; ++i) {
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
queue <int> Q;
Q.push(source);
while (!Q.empty()) {
int node = Q.front();
Q.pop();
for (auto x : graph[node]) {
if (distance[x] > distance[node] + 1) {
distance[x] = distance[node] + 1;
Q.push(x);
}
}
}
for (int i = 1; i <= n; ++i) {
fout << (distance[i] == 1000000000 ? -1 : distance[i]) << ' ';
}
return 0;
}