Cod sursa(job #278330)

Utilizator alex3el_n2oAlex Vladescu alex3el_n2o Data 12 martie 2009 11:26:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <stdio.h>
#define nmax 100005
struct nod
{
	int varf;
	nod *adr;
} *q[nmax],*in[nmax];
long d[nmax],c[nmax];
int use[nmax];

void add(long x, long y)
{
	nod *aux;
	aux=new nod;
	aux->varf=y;
	aux->adr=q[x];
	q[x]=aux;
}

void bf(int a)
{
	nod *aux;
	long in,sf,b;
	in=1;
	sf=1;
	c[in]=a;
	use[a]=1;
	d[a]=0;
	while (in<=sf)
	{
		b=c[in];
		aux=q[b];
		while (aux!=NULL)
		{
			if (!use[aux->varf])
			{
				c[++sf]=aux->varf;
				use[aux->varf]=1;
				d[aux->varf]=d[b]+1;
			}
			aux=aux->adr;
		}
		in++;
	}
}
		
int main()
{
	freopen("bfs.in","r",stdin);
	freopen("bfs.out","w",stdout);
	long i,n,m,s,a,b;
	scanf("%ld%ld%ld",&n,&m,&s);
	for (i=1;i<=m;i++)
	{
		scanf("%ld %ld",&a,&b);
		add(a,b);
	}
	bf(s);
	for (i=1;i<=n;i++)
			if (i==s) printf("0 ");
			else if (d[i]==0) printf("-1 ");
			else printf("%d ",d[i]);
	printf("\n");
}