Pagini recente » Cod sursa (job #455596) | Cod sursa (job #1633366) | Cod sursa (job #3156948) | Cod sursa (job #2848974) | Cod sursa (job #1504644)
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
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 );
for ( i = 1 ; i <= M ; i ++ )
{
fscanf ( f , "%d %d" , &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 [ current ] < cost [ edge [ current ] [ i ] ] )
{
//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 )
fprintf ( g , "-1 " );
else
fprintf ( g , "%d " , cost [ i ] );
}
int main()
{
read();
for ( i = 1 ; i <= N ; i ++ )
cost [ i ] = INF;
bfs ( S );
printf();
return 0;
}