Cod sursa(job #493937)

Utilizator DuxarFII-Stefan-Negrus Duxar Data 19 octombrie 2010 22:38:51
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include<cstdio>
using namespace std;

struct NodLSI
{
	int inf;
	struct NodLSI* next;
} ;

typedef NodLSI* LSI;

LSI NS[100001];

int N,M,S,viz[100001],C[100001],p,u;

void adaug(int x,int y);
void read();
void write();
void solve();

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

void read()
{
	int i,x,y;
	scanf("%ld%ld%ld",&N,&M,&S);
	for (i=1;i<=M;++i)
	{
		scanf("%ld%ld",&x,&y);
		adaug(x,y);
	}
}

void adaug(int x,int y)
{
	LSI p=new NodLSI;
	p->inf=y;
	p->next=NS[x];
	NS[x]=p;
}

void solve()
{
	LSI i;
	int z;
	p=u=1;
	C[p]=S;
	while (p<=u)
	{
		z=C[p++];
		for (i=NS[z];i;i=i->next)
			if (!viz[i->inf]&&i->inf!=S&&i->inf!=z)
			{
				C[++u]=i->inf;
				viz[i->inf]=viz[z]+1;
			}
	}
}

void write()
{
	int i;
	for (i=1;i<=N;++i)
	if (viz[i]==0&&i!=S) printf("%ld ",-1);
	else printf("%ld ",viz[i]);
}