Cod sursa(job #627339)
#include<fstream>
#include<vector>
using namespace std;
vector <int> a[100001];
int v[100001], nivel[100001], top, N, M, s;
bool viz[100001];
void BFS(){
int i, pr = 0, ul = 0, nod, start = s;
v[ul] = start;
viz[s] = true;
while (pr <= ul){
start = v[pr++];
for (i = 0; i < a[start].size(); i++){
nod = a[start][i];
if (!viz[nod]){
v[++ul] = nod;
viz[nod] = true;
nivel[nod] = nivel[start] + 1;
}
}
}
for (i = 1; i <= N ; i++) if ( (i != s) && (nivel[i] == 0)) nivel[i] = -1;
}
int main(){
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int i, x, y;
fin >> N >> M >> s;
for (i = 0 ; i < M; i++){
fin >> x >> y;
a[x].push_back(y);
}
BFS();
for (i = 1; i <= N; i++){
fout<<nivel[i]<<" ";
}
fout.close();
return 0;
}