Cod sursa(job #1641113)

Utilizator serbanSlincu Serban serban Data 8 martie 2016 21:02:33
Problema Ciclu Eulerian Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 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< pair<int, int> > L[100005];
vector< pair<int, int> > M[500005];
stack<int> s;

vector<int> ans;

bool viz[100005];
stack<int> df;

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, i});
        L[y].push_back({x, i});
        M[i].push_back({x, y});
    }

    for(int i = 1; i <= n; i ++) {
        if(L[i].size() & 1) {
            g << "-1\n";
            return 0;
        }
    }
    df.push(1);
    while(!df.empty()) {
        int v = df.top(); df.pop();
        viz[v] = true;
        for(int i = 0; i < L[v].size(); i ++) {
            if(!viz[L[v][i].first]) df.push(L[v][i].first);
        }
    }
    for(int i = 1; i <= n; i ++) {
        if(!viz[i]) {
            g << "-1\n";
            return 0;
        }
    }

    s.push(1);
    while(!s.empty()) {
        int top = s.top(), i;
        for(i = 0; i < L[top].size(); i ++) {
            int cur = L[top][i].first;
            int muc = L[top][i].second;
            if(!vm[muc]) s.push(cur), vm[muc] = true, i = oo;
        }
        if(i != oo + 1) {
            ans.push_back(top);
            s.pop();
        }
    }
    for(int i = ans.size() - 1; i > 0; i --) g << ans[i] << " ";
    g << "\n";
    return 0;
}