Cod sursa(job #2775610)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 16 septembrie 2021 15:31:00
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");

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

const int N = 1e5 + 5;

vector < int > a[N];

void bfs(int k, int n)
{
    vector < int > d(N, 2e9);
    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);
            }
        }
    }
    for(int i = 1; i <= n; ++i) {
        fout << (d[i] != 2e9 ? d[i] : -1) << " ";
    }
}

int main()
{
    usain_bolt();

    int n, m, k;

    fin >> n >> m >> k;
    for(; m; --m) {
        int x, y;

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