Cod sursa(job #593344)

Utilizator thesilverhand13FII Florea Toma Eduard thesilverhand13 Data 2 iunie 2011 12:32:14
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
 # include <fstream>
 # include <vector>
 # include <algorithm>
 # define dim 100002
 # define pb push_back
 
 using namespace std;
 
 ifstream f ("bfs.in");
 ofstream g ("bfs.out");
 
 vector <int> a[dim];
 int viz[dim], c[dim], G[dim];
 int n, m, s;
 
 void citire()
 {
	 int i, x, y;
	 f >> n >> m >> s;
	 for ( i = 1 ; i <= m ; ++ i )
	 {
		 f >> x >> y;
		 a[ x ].pb( y );
	 }
	 
	 for ( i = 1 ; i <= n ; ++ i )
		 G[ i ] = a[ i ].size();
	 
	 for ( i = 1 ; i <= n ; ++ i )
		 c[ i ] = -1;
	 
 }

 void bfs(int x)
 {
	 int i, j, l;
	 l = 1;
	 c[ x ] = 0;
	 viz[ l ] = x;
	 for ( i = 1 ; i <= l ; ++ i)
		 for ( j = 0; j < G[ viz[ i ] ]; ++ j)
			 if(c[ a[ viz[ i ] ][ j ] ] == -1 )
			 {
				 l++;
				 viz[ l ] = a[ viz[ i ] ][ j ];
				 c[ viz[ l ] ] = c[ viz[ i ] ] + 1;	
			 }
 }
 
 void afisare()
 {
	 int i;
	 for( i = 1 ; i <= n ; ++ i )
		 g<<c[ i ]<<" ";
	 g<<"\n";
 }
 
 int main()
 {
	 citire();
	 bfs(s);
	 afisare();
	 return 0;
 }