Cod sursa(job #1477518)

Utilizator xtreme77Patrick Sava xtreme77 Data 26 august 2015 14:49:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
/**
 * Code by Patrick Sava
 * "Spiru Haret" National College of Bucharest
 **/

# include "fstream"
# include "cstring"
# include "vector"
# include "queue"
# include "bitset"
# include "algorithm"
# include "map"
# include "unordered_map"
# include "deque"
# include "string"
# include "iomanip"
# include "cmath"
# include "stack"
# include "cassert"

const char IN [ ] =  "bfs.in" ;
const char OUT [ ] = "bfs.out" ;
const int MAX = 100999 ;

# define pb push_back
# define mp make_pair
# define FORN( a , b , c ) for ( int a = b ; a <= c ; ++ a )
# define FORNBACK( a , b , c ) for ( int a = b ; a >= c ; -- a )

using namespace std ;

ifstream cin ( IN ) ;
ofstream cout ( OUT ) ;

vector < int > gr [ MAX ] ;

queue < int > Q ;

int dist [ MAX ] ;

int main()
{
    int n , m , s ;
    cin >> n >> m >> s ;

    while ( m -- )
    {
        int x , y ;
        cin >> x >> y ;
        gr [ x ].pb ( y ) ;
    }

    FORN ( i , 1 , n ) dist [ i ] = 1 << 30 ;

    Q.push ( s ) ;
    dist [ s ] = 0 ;

    while ( !Q.empty() )
    {
        int nod = Q.front() ;
        Q.pop() ;

        for ( auto x : gr [ nod ] )
        {
            if ( dist [ x ] > dist [ nod ] + 1 )
            {
                dist [ x ] = dist [ nod ] + 1 ;
                Q.push ( x ) ;
            }
        }
    }

    FORN ( i , 1 , n )
        if ( dist [ i ] == 1 << 30 )
            cout << -1 << ' ' ;
        else cout << dist [ i ] << ' ' ;


    return 0;
}