Cod sursa(job #3309533)

Utilizator alesiodemiriAlesio Demiri alesiodemiri Data 6 septembrie 2025 11:04:51
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>

using namespace std;

#define ll long long

int n, m;
vector<vector<int>> graph;
vector<int> path; 
vector<multiset<int>> adj; // use multiset to remove edges one by one

void ReadData() {
    cin >> n >> m;
    graph.assign(n, vector<int>());
    adj.assign(n, multiset<int>());

    for (int i = 0; i < m; i++) {
        int start = 0, end = 0;
        cin >> start >> end ;
        start--; end--;
        if (start != end) {
            graph[start].push_back(end);
            graph[end].push_back(start);
            adj[start].insert(end);
            adj[end].insert(start);
        } else {
            graph[start].push_back(end);
            adj[start].insert(end);
        }
    }
}

void Solve() {
    int start = -1;

    // choose start vertex
    for (int i = 0; i < n; i++) {
        if (adj[i].size() % 2 == 1) {
            start = i;
            break;
        }
    }
    if (start == -1) { // no odd degree
        for (int i = 0; i < n; i++) {
            if (!adj[i].empty()) {
                start = i;
                break;
            }
        }
    }
    if (start == -1) { // graph has no edges at all
        cout << "-1\n";
        return;
    }

    stack<int> st;
    vector<int> res;

    st.push(start);
    while (!st.empty()) {
        int v = st.top();
        if (!adj[v].empty()) {
            int u = *adj[v].begin();
            adj[v].erase(adj[v].find(u));
            if (u != v) { // important fix for self-loops
                adj[u].erase(adj[u].find(v));
            }
            st.push(u);
        } else {
            res.push_back(v);
            st.pop();
        }
    }

    if ((int)res.size() != m + 1) {
        cout << "-1\n";
        return;
    }

    for (int i = res.size() - 1; i >= 0; i--) {
        cout << res[i] + 1 << " ";
    }
    cout << "\n";
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("cyclueuler.in", "r", stdin);
    freopen("cyclueuler.out", "w", stdout);

    int t = 1;
    // cin >> t; // Uncomment for multiple test cases
    while (t--) {
        ReadData();
        Solve();
    }
    return 0;
}