Pagini recente » Cod sursa (job #2881726) | Cod sursa (job #3000734) | Cod sursa (job #2271150) | Cod sursa (job #583686) | Cod sursa (job #420563)
Cod sursa(job #420563)
#include <cstdio>
#include <vector>
#include <list>
using namespace std;
#define MAX 100005
FILE* fout=fopen("bfs.out","w");
vector<int>nod[MAX];
int dist[MAX],n,m,s;
//<parsing>
FILE* fin=fopen("bfs.in","r");
const unsigned maxb=8192;
char buf[maxb];
unsigned ptr=0;
inline unsigned getInt(){
unsigned nr=0;
while(buf[ptr]<'0'||'9'<buf[ptr])
if(++ptr>=maxb)
fread(buf,maxb,1,fin),ptr=0;
while('0'<=buf[ptr]&&buf[ptr]<='9'){
nr=nr*10+buf[ptr]-'0';
if(++ptr>=maxb)
fread(buf,maxb,1,fin),ptr=0;
}
return nr;
}
//</parsing>
void bfs(int beg){
list<int> lst;
lst.push_back(beg);
dist[beg]=0;
while(lst.size()>0){
beg=lst.front();
for(int i=0;i<nod[beg].size();i++){
if(dist[nod[beg][i]]==-1){
dist[nod[beg][i]]=dist[beg]+1;
lst.push_back(nod[beg][i]);
}
}
lst.pop_front();
}
}
int main(){
int x,y;
n=getInt(),m=getInt(),s=getInt();
for(int i=0;i<m;i++){
x=getInt(),y=getInt();
nod[x-1].push_back(y-1);
}
for(int i=0;i<n;i++)
dist[i]=-1;
bfs(s-1);
for(int i=0;i<n;i++)
fprintf(fout,"%d ",dist[i]);
fclose(fin);
fclose(fout);
return 0;
}