Cod sursa(job #2831181)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 10 ianuarie 2022 21:53:52
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
using ll = long long;

const string fn = "bfs";


ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

int n, m, source;

int d[100005];

bitset<100005> viz;
vector<int> g[100005];

void bfs(int nod) {
    queue<int> q;
    q.push(nod);
    viz[nod] = true;
    while (!q.empty()) {
        nod = q.front();
        q.pop();
        for (int fiu : g[nod]) {
            if (!viz[fiu]) {
                viz[fiu] = true;
                d[fiu] = d[nod] + 1;
                q.push(fiu);
            }
        }
    }
}

int main() {

    int x, y;

    fin >> n >> m >> source;

    while (m--) {
        fin >> x >> y;
        g[x].pb(y);
    }

    for (int i = 1; i <= n; ++i)
        d[i] = 2e9;

    d[source] = 0;
    bfs(source);

    for (int i = 1; i <= n; ++i)
        if (d[i] == 2e9)
            fout << -1 << " ";
        else
            fout << d[i] << " ";

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