Pagini recente » Cod sursa (job #769597) | Cod sursa (job #601257) | Cod sursa (job #309788) | tema | Cod sursa (job #3157765)
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;
const int nrnoduri = 1000000;
vector<int> g[nrnoduri + 1];
int vizitati[nrnoduri + 1], distanta[nrnoduri + 1];
void BFS(int x) {
queue<int> q;
q.push(x);
vizitati[x] = 1;
distanta[x] = 0;
while (!q.empty()) {
x = q.front();
q.pop();
for (auto next : g[x]) {
if (!vizitati[next]) {
q.push(next);
vizitati[next] = 1;
distanta[next] = distanta[x] + 1;
}
}
}
}
int main() {
ifstream f("bfs.in");
ofstream h("bfs.out");
int N, M, S;
f >> N >> M >> S;
for (int i = 1; i <= M; i++) {
int x, y;
f >> x >> y;
g[x].push_back(y);
}
BFS(S);
for (int i = 1; i <= N; i++) {
if (i != S && distanta[i] == 0) h << -1 << " ";
else h << distanta[i] << " ";
}
return 0;
}