Cod sursa(job #767701)
#include <fstream>
#include <vector>
#include <queue>
#define maxn 100010
using namespace std;
unsigned long N,M,S;
unsigned long Viz[maxn],Cost[maxn];
queue <unsigned long> Q;
vector <unsigned long> V[maxn];
void BFS(unsigned long nod){
Q.push(nod);
Viz[nod]=1;
while(!Q.empty()){
nod=Q.front();
Q.pop();
for(vector<unsigned long>::iterator it=V[nod].begin();it!=V[nod].end();++it)
if(Viz[*it]==-1){
Q.push(*it);
Viz[*it]=1;
Cost[*it]=Cost[nod]+1;
}
}
}
int main(){
ifstream f("bfs.in");
ofstream g("bfs.out");
unsigned long x,y;
f>>N>>M>>S;
for(unsigned long i=1;i<=M;i++){
f>>x>>y;
V[x].push_back(y);
Viz[i]=-1;
}
BFS(S);
for(unsigned long i=1;i<=N;i++)
if(Cost[i]==0&&i!=S)
g<<-1<<' ';
else
g<<Cost[i]<<' ';
g<<'\n';
g.close();
return 0;
}