Cod sursa(job #2817441)

Utilizator schizofrenieShallan Davar schizofrenie Data 13 decembrie 2021 18:05:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

constexpr size_t MAXNODE = 100000;

std::array<std::vector<int>, MAXNODE> edges;
std::array<bool, MAXNODE> vis;
std::array<int, MAXNODE> nb_of_arcs_to;

void
bfs (int start) {
    std::queue<int> q({start});

    vis[start] = true;
    nb_of_arcs_to[start] = 0;
    while (!q.empty()) {
        int now = q.front();
        q.pop();

        for (auto to: edges[now])
            if (!vis[to]) {
                nb_of_arcs_to[to] = nb_of_arcs_to[now] + 1;
                q.emplace(to);
                vis[to] = true;
            }
    }
}

int main () {
    int n, m, s;
    std::ifstream f("bfs.in");
    std::ofstream g("bfs.out");

    f >> n >> m >> s;
    -- s;

    for (int i = 0; i != m; ++ i) {
        int from, to;
        f >> from >> to;
        -- from, -- to;

        edges[from].emplace_back(to);
    }

    nb_of_arcs_to.fill(-1);
    bfs(s);

    for (int i = 0; i != n; ++ i)
        g << nb_of_arcs_to[i] << ' ';
}