Cod sursa(job #745371)

Utilizator fhandreiAndrei Hareza fhandrei Data 11 mai 2012 12:34:46
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
//Include
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

//Definitii
#define pb push_back

//Constante
const int MAX_SIZE = (int)1e5+1;

//Variabile
ifstream in("bfs.in");
ofstream out("bfs.out");

int nodes, edges, startNode;
int dist[MAX_SIZE];

vector<int> graph[MAX_SIZE];
queue<int> q;

//Main
int main()
{
	in >> nodes >> edges >> startNode;
	
	int cFrom, cTo;
	while(edges--)
	{
		in >> cFrom >> cTo;
		graph[cFrom].pb(cTo);
	}
	
	q.push(startNode);
	dist[startNode] = 1;
	
	while(!q.empty())
	{
		int node = q.front();
		q.pop();
		
		vector<int>::iterator it=graph[node].begin(), end=graph[node].end();
		
		for(; it!=end ; ++it)
			if(!dist[*it])
			{
				dist[*it] = dist[node]+1;
				q.push(*it);
			}
	}
	
	for(int i=1 ; i<=nodes ; ++i)
		out << dist[i]-1 << ' ';
	
	in.close();
	out.close();
	return 0;
}