Cod sursa(job #1641162)

Utilizator serbanSlincu Serban serban Data 8 martie 2016 21:19:17
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <stack>
#define oo 1111111

using namespace std;

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

bool vm[500005];
vector<int> L[100005];
stack<int> s;

vector<int> ans;

int main()
{
    int n, m, x, y; f >> n >> m;
    for(int i = 0; i < m; i ++) {
        f >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }

    for(int i = 1; i <= n; i ++) {
        if(L[i].size() & 1) {
            g << "-1\n";
            return 0;
        }
    }

    s.push(1);
    while(!s.empty()) {
        int top = s.top();
        if(L[top].size()) {
            int aux = L[top][ L[top].size() - 1];
            L[top].pop_back();
            for(int j = 0; j < L[aux].size(); j ++) {
                if(L[aux][j] == top) {
                    L[aux][j] = L[aux][L[aux].size() - 1];
                    L[aux].pop_back();
                    j = oo;
                }
            }
            s.push(aux);
        }
        else {
            ans.push_back(top);
            s.pop();
        }
    }
    if(ans.size() != m + 1) {
        g << "-1\n";
        return 0;
    }
    for(int i = ans.size() - 1; i > 0; i --) g << ans[i] << " ";
    g << "\n";
    return 0;
}