Cod sursa(job #3358011)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:56:32
Problema Ciclu Eulerian Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

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

    int n, m;
    input >> n >> m;

    std::vector<std::vector<int>> graph(n + 1);
    std::vector<int> degree(n + 1, 0);

    for (int i = 0; i < m; ++i) {
        int x, y;
        input >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
        degree[x]++;
        degree[y]++;
    }

    bool has_cycle = true;
    for (int i = 1; i <= n; ++i) {
        if (degree[i] % 2 == 1) {
            has_cycle = false;
            break;
        }
    }

    if (!has_cycle) {
        output << -1;
    } else {
        std::vector<std::vector<int>> adj = graph;
        std::vector<int> ptr(n + 1, 0);
        std::vector<int> cycle;
        std::stack<int> st;
        st.push(1);

        while (!st.empty()) {
            int v = st.top();
            if (ptr[v] < (int)adj[v].size()) {
                int u = adj[v][ptr[v]++];
                auto it = std::find(adj[u].begin(), adj[u].end(), v);
                if (it != adj[u].end()) {
                    adj[u].erase(it);
                }
                st.push(u);
            } else {
                cycle.push_back(v);
                st.pop();
            }
        }

        if ((int)cycle.size() != m + 1) {
            output << -1;
        } else {
            for (int i = (int)cycle.size() - 1; i >= 0; --i) {
                output << cycle[i] << " ";
            }
        }
    }

    return 0;
}