Cod sursa(job #2868281)

Utilizator the_horoHorodniceanu Andrei the_horo Data 10 martie 2022 20:37:41
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <algorithm>
#include <array>
#include <cstdint>
#include <fstream>
#include <queue>
#include <vector>


using i32 = int32_t;
using u32 = uint32_t;

constexpr size_t MAX_NODES = 100000;


constexpr i32 INF_PATH = 0x7fffffff;


size_t nodeCount;
std::array<std::vector<size_t>, MAX_NODES> edges;


std::vector<i32> bfs (size_t start) {
    std::vector<i32> pathLength(nodeCount, INF_PATH);

    pathLength[start] = 0;
    std::queue<size_t> q({start});

    while (!q.empty()) {
        size_t node = q.front();
        q.pop();

        for (auto to: edges[node])
            if (pathLength[to] == INF_PATH) {
                pathLength[to] = pathLength[node] + 1;
                q.emplace(to);
            }
    }

    std::replace(pathLength.begin(), pathLength.end(), INF_PATH, -1);

    return pathLength;
}


int main () {
    std::ifstream in("bfs.in");
    std::ofstream out("bfs.out");

    size_t edgeCount, startNode;
    in >> nodeCount >> edgeCount >> startNode;
    -- startNode;

    for (size_t i = 0; i != edgeCount; ++ i) {
        size_t x, y;
        in >> x >> y;
        -- x, -- y;

        edges[x].emplace_back(y);
    }

    const auto result = bfs(startNode);
    for (auto val: result)
        out << val << ' ';
}