Cod sursa(job #1109597)

Utilizator zaharia_horiaZaharia Horia zaharia_horia Data 17 februarie 2014 13:26:50
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include<fstream>
#include<vector>
#include<queue>

using namespace std;

ifstream fin( "bfs.in" );
ofstream fout( "bfs.out" );

const int nmax = 100000;
int v[nmax+1];

vector <int> g[nmax+1];
queue <int> q;

void bfs( int s ) {
    q.push( s );
    while ( !q.empty() ) {
        int w = q.front();
        q.pop();
        for( int i = 0; i < (int)g[w].size(); ++ i ) {
            int x = g[w][i];
            if ( v[ x ] == 0 && x != s ) {
                v[ x ] = v[ w ] + 1;
                q.push( x );
            }
        }
    }

}
int main()
{
    int n, m, a, b, s;
    fin>>n>>m>>s;
    for( int i = 0; i < m; ++ i ) {
        fin>>a>>b;
        g[a].push_back( b );
    }
    bfs( s );
    for( int i = 1; i <= n; ++ i ) {
        if ( v[i] == 0 && i != s )
            fout<<"-1 ";
        else
            fout<<v[i]<<' ';
    }
    fout<<'\n';
    fin.close();
    fout.close();
    return 0;
}