Cod sursa(job #2987149)

Utilizator the_horoHorodniceanu Andrei the_horo Data 1 martie 2023 23:31:29
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <array>
#include <bitset>
#include <cstdint>
#include <forward_list>
#include <fstream>
#include <utility>
#include <vector>


constexpr size_t MAX_NODES = 100000;
constexpr size_t MAX_EDGES = 500000;


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



std::bitset<MAX_EDGES> used;

bool edgesLeft (size_t node) {
    while (!edges[node].empty() && used[edges[node].back().second])
        edges[node].pop_back();
    return !edges[node].empty();
}

constexpr size_t NO_MORE_EDGES = -1;
size_t getNextNode (size_t node) {
    if (edgesLeft(node)) {
        auto [toNode, edgeIndex] = edges[node].back();
        edges[node].pop_back();
        used[edgeIndex] = true;
        return toNode;
    }
    return NO_MORE_EDGES;
}

bool isEulerianGraph () {
    for (const auto &neighbours: edges)
        if (neighbours.size() % 2 != 0)
            return false;
    return true;
}


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

    size_t nodeCount, edgeCount;
    in >> nodeCount >> edgeCount;

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

        edges[x].emplace_back(y, i);
        edges[y].emplace_back(x, i);
    }

    if (!isEulerianGraph()) {
        out << "-1\n";
        return 0;
    }

    std::forward_list<size_t> result({0});
    for (auto it = result.begin(); it != result.end();) {
        if (!edgesLeft(*it)) {
            ++ it;
            continue;
        }

        size_t node = *it;
        do {
            result.emplace_after(it, node);
            node = getNextNode(node);
        } while (node != NO_MORE_EDGES);
    }

    result.pop_front();
    for (const auto &node: result)
        out << node + 1 << ' ';
}