Cod sursa(job #1125706)

Utilizator superman_01Avramescu Cristian superman_01 Data 26 februarie 2014 19:06:49
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>

#define MAX_SIZE 100005
#define INF 0x3f3f3f3f

using namespace std;

typedef vector < int > ::iterator vii;

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

vector < int > G[MAX_SIZE] ;
int N ,M ,ccount , cost[MAX_SIZE] , S;
queue < int > Q;

void BFS ( void )
{
	memset ( cost , INF , sizeof ( cost));
	cost[S] = 0 ;
	Q.push(S);
	for ( ; !Q.empty() ; )
	{
		int node = Q.front(); Q.pop();
		for ( vii it = G[node].begin() ; it != G[node].end() ; ++it )
			if(  cost[*it] > cost[node] + 1 )
		       cost[*it] = cost[node] + 1 , Q.push ( *it ) ;
	}
}

int main ( void )
{
	int i , j  , x , y;
	in >> N >> M >> S ;
	for ( i = 1 ; i <= M ; ++i )
	{
	    in >> x >> y; 
		G[x].push_back(y);
	}
	BFS();
 	for ( i = 1 ; i <= N ; ++i )
		out << ( cost[i] == INF ? -1 : cost[i] ) << " ";
	in.close();
	out.close();
	return 0 ;	
}