Cod sursa(job #497721)

Utilizator AndreiRSStatescu Andrei Rares AndreiRS Data 3 noiembrie 2010 10:39:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <stdio.h>
#include <list>
using namespace std;
#define DIM 100001

list <int> V[DIM];
list <int> C;
list <int> :: iterator It;

int N, M, S;
int dist[DIM];

void cit ()
{
	int x, y;	
	scanf ("%d%d%d", &N, &M, &S);
	for (int i = 0; i < M; ++i)
	{
		scanf ("%d%d", &x, &y);
		V[x].push_back (y);
	}
}

void coada ()
{
	int X, Y;
	C.push_back (S);
	
	while ( !C.empty () )
	{
		X = C.front ();
		C.pop_front ();
		
		for (It = V[X].begin (); It != V[X].end (); ++It)
		{
			Y = *It;
			if ( Y == S ) continue;
			if ( !dist[Y] )
			{
				C.push_back (Y);
				dist[Y] = dist[X] + 1;
			}			
		}		
	}	
}

void afs ()
{
	for (int i = 1; i <= N; ++i)
		if ( dist[i] ) printf ("%d ", dist[i]);
		else
			if ( i == S ) printf ("%d ", dist[i]);
			else printf ("-1 ");
}

int main ()
{
	freopen ("bfs.in", "r", stdin);
	freopen ("bfs.out", "w", stdout);
	
	cit ();
	coada ();
	afs ();	
}