Cod sursa(job #2568679)

Utilizator 12222Fendt 1000 Vario 12222 Data 4 martie 2020 09:21:27
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>

using namespace std;

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

const int Nmax = 1e5 + 5;
const int oo = 2e9;

int n, m, start;
int dist[Nmax];
vector <int> L[Nmax];
queue <int> q;

int main()
{
    fin >> n >> m >> start;

    int x, y;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;

        L[x].push_back(y);
    }

    for(int i = 1; i <= n; i++)
        dist[i] = oo;

    dist[start] = 0;
    q.push(start);

    while(!q.empty())
    {
        x = q.front();
        q.pop();

        for(auto i : L[x])
            if(dist[i] > dist[x] + 1)
            {
                dist[i] = dist[x] + 1;
                q.push(i);
            }
    }

    for(int i = 1; i <= n; i++)
        fout << (dist[i] == oo ? -1 : dist[i]) << " ";

    fin.close();
    fout.close();
    return 0;
}