Cod sursa(job #326259)

Utilizator IoannaPandele Ioana Ioanna Data 24 iunie 2009 13:48:16
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include<stdio.h>
long n,m,s;
long q[100010],v[100010];

struct nod
{
nod *urm;
long info;
};

nod *top[100010];

void InsertBegin(long x,long y)
{
nod *aux;
aux=new nod;
aux->urm=top[x];
aux->info=y;
top[x]=aux;
}

void read()
{
long x,y;
scanf("%ld%ld%ld",&n,&m,&s);
long i;
for (i=1;i<=m;i++)
    {
     scanf("%ld%ld",&x,&y);
     InsertBegin(x,y);
    }
}

void bfs()
{
long st,dr;
nod *p;
st=dr=1;
v[s]=1;
q[1]=s;
while (st<=dr)
      {
       for (p=top[q[st]];p!=NULL;p=p->urm)
           {
            if (!v[p->info])
               {
                v[p->info]=v[q[st]]+1;
                q[++dr]=p->info;
               }
           }
      st++;
      }
}

void print()
{
long i;
for (i=1;i<=n;i++)
    {
     printf("%ld ",v[i]-1);
    }
}

int main()
{
freopen("bfs.in","r",stdin);
freopen("bfs.out","w",stdout);
read();
bfs();
print();
return 0;
}