Pagini recente » Cod sursa (job #433811) | Cod sursa (job #3147626) | Cod sursa (job #2585490) | Cod sursa (job #1504663)
#include <fstream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
ifstream f ( "bfs.in" );
ofstream g ( "bfs.out" );
//FILE *f = fopen ( "bfs.in" , "r" ) , *g = fopen ( "bfs.out" , "w" );
const int MAX = 100005 , INF = 1000005;
int N , M , S , cost [ MAX ] , i , node1 , node2 ,current;
vector <int> edge [ MAX ];
queue <int> explore;
//bool vis [ MAX ];
void read()
{
//fscanf ( f , "%d %d %d" , &N , &M , &S );
f >> N >> M >> S;
for ( i = 1 ; i <= M ; i ++ )
{
//fscanf ( f , "%d %d" , &node1 , &node2 );
f >> node1 >> node2;
edge [ node1 ] . push_back ( node2 );
}
}
void bfs ( int source )
{
//insert the source vertex in the queue
explore . push ( source );
cost [ source ] = 0;
while ( !explore . empty () )
{
//need to expand current
current = explore . front();
//vis [ current ] = true;
//explore the current node
for ( i = 0 ; i < edge [ current ] . size() ; i ++ )
if ( /*vis [ edge [ current ] [ i ] ] == false*/ cost [ edge [ current ] [ i ] ] == INF )
{
//add the node to the queue
explore . push ( edge [ current ] [ i ] );
cost [ edge [ current ] [ i ] ] = cost [ current ] + 1;
}
//pop current from the queue
explore . pop ();
}
}
void printf()
{
for ( i = 1 ; i <= N ; i ++ )
{
if ( cost [ i ] == INF )
cost [ i ] = -1;
//fprintf ( g , "%d " , cost [ i ] );
g << cost[i] << " ";
}
}
int main()
{
read();
for ( i = 1 ; i <= N ; i ++ )
cost [ i ] = INF;
bfs ( S );
printf();
return 0;
}