Cod sursa(job #2212005)

Utilizator CryshanaGanea Carina Cryshana Data 12 iunie 2018 19:37:05
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;

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

const int N = 100001;
int d[N];
vector <int> v[N], a[N];
queue <int> q;

int main ()
{
    int n, m, s;
    fin >> n >> m >> s;
    for ( int i = 0; i < m; i++ )
    {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
    }
        for ( int j = 1; j <= n; j ++ )
        {
            d[j] = N + 1;
        }
        q.push(s);
        d[s] = 0;
        while ( !q.empty() )
        {
            int x = q.front();
            q.pop();
            for ( int k = 0; k < a[x].size() ; k++ )
            {
                int y = a[x][k];
                if ( d[y] == N + 1 )
                {
                    q.push(y);
                    d[y] = d[x] + 1;
                }
            }
        }
    for ( int i = 1; i <= n; i++ )
    {
        if ( d[i] == N + 1 )
        {
            fout << "-1 ";
        }
        else
            {
                fout << d[i] << " ";
            }
    }
    return 0;
}