Pagini recente » Monitorul de evaluare | Monitorul de evaluare | Cod sursa (job #1427454)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ( "bfs.in" ) ;
ofstream fout ( "bfs.out" ) ;
const int MAX = 100014 ;
int dist [ MAX ] ;
vector < int > gr [ MAX ] ;
queue < int > Q ;
int main ( void )
{
int n , m , Sursa ;
fin >> n >> m >> Sursa ;
for ( int i = 1 ; i <= m ; ++ i )
{
int x , y ;
fin >> x >> y ;
gr [ x ].push_back ( y ) ;
}
for ( int i = 1 ; i <= n ; ++ i )
dist [ i ] = 1000000000 ;
dist [ Sursa ] = 0 ;
Q.push ( Sursa ) ;
while ( Q.empty() == 0 )
{
int nod = Q.front ( ) ;
Q.pop ( ) ;
for ( auto x : gr [ nod ] )
{
if ( dist [ nod ] + 1 < dist [ x ] )
{
dist [ x ] = dist [ nod ] + 1 ;
Q.push ( x ) ;
}
}
}
for ( int i = 1 ; i <= n ; ++ i )
if ( dist [ i ] == 1000000000 )
fout << "-1 " ;
else fout << dist [ i ] << ' ' ;
return 0;
}