Cod sursa(job #3281231)

Utilizator Verigul1237Veres Andrei Verigul1237 Data 28 februarie 2025 18:22:48
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <vector>
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);
        }
    }
}
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
int main()
{
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> 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) {
            fout << -1;
            return 0;
        }
    }

    buildCycle(1);

    cycle.pop_back();

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