Cod sursa(job #562192)

Utilizator AndreiRSStatescu Andrei Rares AndreiRS Data 22 martie 2011 16:15:03
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <stdio.h>
#include <list>
#include <deque>
using namespace std;

const int DIM = 100005;

int N, M, Dst[DIM];
struct nod { int n, d; } S;

deque <nod> D;
list <int> V[DIM];

void bfs ()
{
	nod x;
	list <int> :: iterator it;
	
	D.push_back (S);
	Dst[S.n] = 0;
	
	while (!D.empty ())
	{
		for (it = V[D.front().n].begin(); it != V[D.front().n].end(); it++)
			if (Dst[*it] == -1)
			{
				x.n = *it;
				x.d = D.front().d + 1;
				D.push_back (x);
				Dst[x.n] = x.d;
			}
		D.pop_front ();
	}	
}

int main ()
{
	freopen ("bfs.in", "r", stdin);
	freopen ("bfs.out", "w", stdout);
	
	scanf ("%d%d%d", &N, &M, &S.n);
	for (int i = 0, a, b; i < M; i++)
	{
		scanf ("%d%d", &a, &b);
		V[a].push_back (b);
		V[b].push_back (a);		
	}
	for (int i = 1; i <= N; i++)
		Dst[i] = -1;
	
	bfs ();
	
	for (int i = 1; i <= N; i++)
		printf ("%d ", Dst[i]);
	
	return 0;
}