Pagini recente » Cod sursa (job #1157217) | Cod sursa (job #122847) | Cod sursa (job #976425) | Cod sursa (job #375995) | Cod sursa (job #1714767)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 100005
#define INF 0x3F3F3F3F
using namespace std;
int N, M, S, ans[NMAX];
vector <int> graph[NMAX];
void read() {
int x, y;
cin >> N >> M >> S;
for (int i = 1; i <= M; ++i) {
cin >> x >> y;
graph[x].push_back(y);
}
memset(ans, INF, sizeof(ans));
ans[S] = 0;
}
void bfs(int root) {
queue <int> q;
vector <int> :: iterator it;
int node;
q.push(root);
while (!q.empty()) {
node = q.front();
q.pop();
for (it = graph[node].begin(); it != graph[node].end(); ++it) {
if (ans[*it] > ans[node] + 1) {
ans[*it] = ans[node] + 1;
q.push(*it);
}
}
}
}
void print() {
for (int i = 1; i <= N; ++i) {
if (ans[i] == INF) {
cout << "-1 ";
continue;
}
cout << ans[i] << " ";
}
}
int main() {
freopen("bfs.in", "r", stdin);
freopen("bfs.out", "w", stdout);
read();
bfs(S);
print();
}