Cod sursa(job #1626662)
Utilizator | Data | 3 martie 2016 11:04:16 | |
---|---|---|---|
Problema | BFS - Parcurgere in latime | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.22 kb |
#include <fstream>
using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");
typedef struct nod{
int inf;
nod* next;
}* grf;
grf a[100005];
int v[100005],cost[100005],N,M,S;
void add(grf &n, int v){
grf u;
u=new nod;
u->inf=v;
u->next=n;
n=u;
}
void bfs(int s){
cost[s]=0;
int p=0,u=0;
v[p]=s;
while(p<=u){
int x=v[p++];
grf q=a[x];
while(q){
if(cost[q->inf]==-1){
cost[q->inf]=cost[x]+1;
v[++u]=q->inf;
}
q=q->next;
}
}
}
int main() {
cin >> N >> M >> S;
int x,y;
for(int i=0; i<M; i++){
cin >> x >> y;
add(a[x],y);
}
for(int i=1; i<=N; i++){
cost[i]=-1;
}
bfs(S);
for(int i=1; i<=N; i++){
cout << cost[i] << " ";
}
return 0;
}