Cod sursa(job #3333468)

Utilizator ana.veronica13Ana Veronica Draghici ana.veronica13 Data 13 ianuarie 2026 17:23:47
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

vector <pair <int, int>> graph[100005];
int grade[100005];
int visited[100005];
int visitedEdges[500005];
int currentEdge[100005];
vector <int> cycle;

void buildCycle(int node) {
    while (currentEdge[node] < graph[node].size()) {
        pair <int, int> edge = graph[node][currentEdge[node]];
        currentEdge[node] += 1;
        if (visitedEdges[edge.second]) 
          continue;
        visitedEdges[edge.second] = 1;
        buildCycle(edge.first);
    }
    cycle.push_back(node);
}

void dfs(int node) {
    visited[node] = 1;
    for (auto x : graph[node]) {
        if (!visited[x.first]) {
            dfs(x.first);
        }
    }
}

int main()
{
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        graph[x].push_back({y, i});
        graph[y].push_back({x, i});

        grade[x] += 1;
        grade[y] += 1;
    }
    dfs(1);

    for (int i = 1; i <= n; ++i) {
        if (!visited[i] or grade[i] % 2) {
            cout << -1;
            return 0;
        }
    }

    buildCycle(1);

    cycle.pop_back();

    for (auto x : cycle) {
        cout << x << " ";
    }
    return 0;
}