Pagini recente » Cod sursa (job #1764417) | Cod sursa (job #1847841) | Cod sursa (job #1692041) | Cod sursa (job #1153652) | Cod sursa (job #276844)
Cod sursa(job #276844)
#include<stdio.h>
int N,M,S,viz[100000];
int st,sf,niv;
int n[100000];
int coada[100000];
typedef struct Nod
{
int k;
struct Nod *urm;
}*pNod;
pNod v[100001];
void add(pNod &dest,int x)
{
pNod p;
p = new Nod;
p->k=x;
p->urm=dest;
dest=p;
}
void citire()
{
int i,x,y;
FILE *in = fopen("bfs.in","rt");
fscanf(in,"%d %d %d",&N,&M,&S);
for(i=1;i<=N;i++) n[i]=-1;
for(i=1;i<=M;i++)
{
fscanf(in,"%d %d",&x,&y);
add(v[x],y);
}
fclose(in);
}
void bf(int S)
{
int i;
pNod p;
st=sf=1;
n[S]=0;
viz[S]=1;
coada[st]=S;
sf++;
while(st<sf)
{
for(p=v[S];p!=NULL;p=p->urm)
if(v[coada[st]]&&!viz[v[p->k]])
{
viz[p->k]=1;
n[p->k]=n[coada[st]]+1;
coada[sf]=i;
sf++;
}
st++;
}
}
int main()
{
int i,nr=0;
citire();
bf(S);
FILE *out=fopen("bfs.out","wt");
for(i=1;i<=N;i++)
fprintf(out,"%d ",n[i]);
fclose(out);
return 0;
}