Cod sursa(job #1217498)

Utilizator AndreiBarbutaAndrei Barbuta AndreiBarbuta Data 7 august 2014 16:04:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <queue>
#include <vector>

#define IN "bfs.in"
#define OUT "bfs.out"
#define pb push_back
#define p push

const int MAX = 100014 ;

using namespace std;

ifstream fin ( IN ) ;
ofstream fout ( OUT ) ;

queue < int > q ;
vector < int > gr [ MAX ] ;
int v [ MAX ] ;

void bfs ( int nod ) ;

int main( )
{
    int n , m , s , x , y;
    fin >> n >> m >> s ;
    for ( register int i = 1 ; i <= m ; ++ i ){
        fin >> x >> y ;
        gr [ x ].pb ( y ) ;
    }
    bfs ( s ) ;
    for ( register int i = 1 ; i <= n ; ++ i )
        fout << v [ i ] - 1 << ' ' ;
    return 0 ;
}

void bfs ( int nod ){
    q.p ( nod ) ;
    v [ nod ] = 1 ;
    while ( not q.empty ( ) ){
        int x = q.front (  ) ;
        q.pop (  ) ;
        for ( auto it : gr [ x ] )
        if ( ! v [ it ] ){
            q.p ( it ) ;
            v [ it ] = v [ x ] + 1 ;
        }

    }
}