Cod sursa(job #1985548)

Utilizator ArctopusKacso Peter-Gabor Arctopus Data 28 mai 2017 02:06:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define pb push_back

using namespace std;

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

const int NLIM = 1e5 + 10;

int N, M;
int ST;
vector< int > graph[NLIM];
int bfs[NLIM];

int main()
{
    fin >> N >> M >> ST;
    for( int i = 0; i < M; ++i )
    {
        int x, y;
        fin >> x >> y;
        graph[x].pb( y );
        //graph[y].pb( x );
    }

    queue< int > qu;

    bfs[ST] = 1;
    qu.push( ST );
    while( qu.size() )
    {
        int nod = qu.front();
        for( int j = 0; j < graph[nod].size(); ++j )
        {
            int nnod = graph[nod][j];
            if( !bfs[nnod] )
            {
                bfs[nnod] = bfs[nod] + 1;
                qu.push( nnod );
            }
        }
        qu.pop();
    }

    for( int i = 1; i <= N; ++i )
    {
        fout << bfs[i] - 1 << " ";
    }

    return 0;
}