Cod sursa(job #2573000)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 5 martie 2020 15:21:10
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 1e5 + 5;

vector < int > a[N], d(N, 2e9);

void bfs(int k, int n)
{
    queue < int > q;
    d[k] = 0;
    q.push(k);
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(auto v : a[x]) {
            if(d[v] > d[x] + 1) d[v] = d[x] + 1, q.push(v);
        }
    }
    for(int i = 1; i <= n; ++i) {
        fout << ((d[i] != 2e9) ? d[i] : -1) << " ";
    }
}
int main()
{
    usain_bolt();

    int n, m, source;

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

        fin >> x >> y;
        a[x].push_back(y);
    }
    bfs(source, n);
    return 0;
}