Cod sursa(job #3341928)

Utilizator ioanabaduIoana Badu ioanabadu Data 21 februarie 2026 18:01:59
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 100005
#define EMAX 500005

using namespace std;

ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");

int nodes, edges;
vector <int> graph[NMAX];
int to[EMAX], from[EMAX];
bool used[EMAX];

int main (){
    int x, y;

    in >> nodes >> edges;
    for (int i=1; i<=edges; ++i){
        in >> x >> y;

        graph[x].push_back(i);
        graph[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }

    for (int i=1; i<=nodes; ++i){
        if (graph[i].size() % 2 == 1){
            out << "-1";
            return 0;
        }
    }

    vector <int> stack;
    vector <int> ans;
    stack.push_back(1);

    while (!stack.empty()){
        int x = stack.back();
        cout << x << ' ';

        if (graph[x].size()){
            int e = graph[x].back();
            graph[x].pop_back();

            if (used[e] == false){
                used[e] = true;

                int aux;
                if (x != to[e])
                    aux = to[e];
                else aux = from[e];

                stack.push_back(aux);
            }
        }
        else{
            stack.pop_back();
            ans.push_back(x);
        }
    }

    for (int i=0; i<ans.size()-1; ++i)
        out << ans[i] << ' ';

    return 0;
}