Cod sursa(job #3158694)

Utilizator ililogIlinca ililog Data 19 octombrie 2023 17:34:48
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
using namespace std;
#include<iostream>
#include<fstream>
#include<vector>
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

const int NMAX = 100005, MMAX = 500005;
vector<int> G[NMAX];

bool usedEdge[MMAX];
int from[MMAX], to[MMAX];
int n,m;

int main() {
    
    fin >> n >> m;
    
    for (int i = 0; i<m; i++) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(i);
        G[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }
    
    for (int i = 1; i<=n; i++) {
        if (G[i].size() % 2 == 1) {
            fout << "-1\n";
            return 0;
        }
    }
    
    vector<int> ans;
    vector<int> stiva;
    stiva.push_back(1);
   // cout << "push " << 1 << endl;
    
    while (!stiva.empty()) {
        int node = stiva.back();
        if (!G[node].empty()) {
            int e = G[node].back();
            G[node].pop_back();
            if (!usedEdge[e]) {
                usedEdge[e] = 1;
                
                if (from[e] == node) {
                    stiva.push_back(to[e]);
                    //cout << "push " << to[e] << endl;
                } else {
                    stiva.push_back(from[e]);
                    //cout << "push " << from[e] << endl;
                }
                
            }
        } else {
            stiva.pop_back();
            ans.push_back(node);
        }
    }
    
    for (int i = 0; i<ans.size()-1; i++) {
        fout << ans[i] << " ";
    }
    fout << '\n';
    
    return 0;
}