Cod sursa(job #3156061)

Utilizator lolismekAlex Jerpelea lolismek Data 10 octombrie 2023 15:28:36
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

#define pii pair <int, int>

string filename = "ciclueuler";

#ifdef LOCAL
    ifstream fin("input.in");
    ofstream fout("output.out");
#else
    ifstream fin(filename + ".in");
    ofstream fout(filename + ".out");
#endif

const int NMAX = 1e5;

struct Edge{
    int a, b;
}edges[5 * NMAX + 1];

bool viz[5 * NMAX + 1];

vector <int> adj[NMAX + 1];

int main(){

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int a, b;
        fin >> a >> b;
        adj[a].push_back(i);
        adj[b].push_back(i);
        edges[i] = {a, b};
    }

    for(int i = 1; i <= n; i++){
        if((int)adj[i].size() % 2 == 1){
            fout << -1 << '\n';
            return 0;
        }
    }

    stack <int> S;
    S.push(1);

    vector <int> ans;
    while(!S.empty()){
        int node = S.top();

        if((int)adj[node].size() > 0){
            int e = adj[node].back();
            adj[node].pop_back();

            if(!viz[e]){
                viz[e] = true;
                int other = edges[e].a ^ edges[e].b ^ node;
                S.push(other);
            }
        }else{
            ans.push_back(node);
            S.pop();
        }
    }
    ans.pop_back();

    for(int node : ans){
        fout << node << ' ';
    }
    fout << '\n';

    return 0;
}