Cod sursa(job #2723408)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 14 martie 2021 00:11:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 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];

int d[N];

void bfs(int k)
{
    queue < int > q;
    q.push(k);
    d[k] = 0;
    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);
            }
        }
    }
}

int main()
{
    usain_bolt();

    int n, m, base;

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

        fin >> x >> y;
        a[x].push_back(y);
    }
    for(int i = 1; i <= n; ++i) {
        d[i] = 2e9;
    }
    bfs(base);
    for(int i = 1; i <= n; ++i) {
        if(d[i] == 2e9) {
            fout << -1 << " ";
        }
        else fout << d[i] << " ";
    }
    return 0;
}