Cod sursa(job #598802)

Utilizator dspMihaiDespotovici Mihai dspMihai Data 27 iunie 2011 10:45:56
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <stdio.h>
#include <vector>
using namespace std;
#define maxn 100010
long i,j,x,y,N,M,S;
vector <int> A[maxn];
int G[maxn],coada[maxn],cost[maxn];

void bfs(long start)
{
	for (i=1; i<=N; i++) cost[i]=-1;
	long L=1;
	coada[L]=start;
	cost[start]=0;
	for (i=1; i<=L; i++)
	{
		for (j=0; j<G[coada[i]]; j++)
		{
			if (cost[A[coada[i]][j]]==-1)
			{
				coada[++L]=A[coada[i]][j];
				cost[coada[L]]=cost[coada[i]]+1;
			}
		}
	}
}

int main ()
{
	freopen("bfs.in", "r", stdin);
	freopen("bfs.out", "w", stdout);
	scanf("%d %d %d", &N,&M,&S);
	for (i=1; i<=M; i++)
	{
		scanf("%d %d", &x,&y);
		A[x].push_back(y);
	}
	for (i=1; i<=N; i++) G[i]=A[i].size();
	bfs(S);
	for (i=1; i<=N; i++) printf("%d ", cost[i]);
	return 0;
}