Cod sursa(job #1369420)

Utilizator valentinpielePiele Valentin valentinpiele Data 3 martie 2015 01:30:48
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

const int Nmax=100005;
int N, M, S;
vector <int> v[Nmax];
queue <int> coada;
int cost[Nmax];
int x, y;
int t;

int main ()
{
	f >> N >> M >> S;
	
	for(int i = 1; i <= M; i ++)
	{
		f >> x >> y;
		v[x].push_back(y);
	}
	
	coada.push(S);
	cost[S]=1;
	
	while(!coada.empty())
	{
		t=coada.front();
		coada.pop();
		
		for(int i = 0; i < v[t].size(); i ++)
		{
			if(cost[v[t][i]] == 0)
			{	
				coada.push(v[t][i]);
				cost[v[t][i]]=cost[t]+1;
			}
		}
	}
	for( int i = 1; i <= N; i ++ )
		g << cost[i] - 1 << ' ';
	return 0;
}