Cod sursa(job #1529614)

Utilizator serbanSlincu Serban serban Data 21 noiembrie 2015 09:07:09
Problema Ciclu Eulerian Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;

vector<int> L[100005];
int l[100005];
int r[100005];
bool v[100005];
bool M[500005];

stack<int> q;
stack<int> ans;

bool viz[100005];
void dfs(int node) {
    viz[node] = true;
    for(int i = 0; i < L[node].size(); i ++) {
        if(!viz[L[node][i]]) {
            dfs(L[node][i]);
        }
    }
}

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

int main()
{
    int n, m, x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i ++) {
        f >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    bool ok = true;
    for(int i = 1; i <= n; i ++) {
        l[i] = L[i].size();
        if(l[i] & 1)
            ok = false;
    }
    if(!ok) {
        g << "-1\n";
        return 0;
    }
    //verific conexitate
    dfs(1);
    for(int i = 1; i <= n; i ++)
        if(!viz[i]) ok = false;
    if(!ok) {
        g << "-1\n";
        return 0;
    }

    q.push(1);
    while(!q.empty()) {
        int a = q.top();
        if(l[a]) {
            int node = L[a][l[a] - 1];
            q.push(node);
            for(int i = 0; i < l[node]; i ++) {
                if(L[node][i] == a) {
                    L[node][i] = L[node][l[node] - 1];
                    l[node] --;
                    i = l[node];
                }
            }
            l[a] --;
        }
        else {
            ans.push(a);
            q.pop();
        }
    }
    while(ans.size() != 1) {
        g << ans.top() << " ";
        ans.pop();
    }
    g << "\n";
    return 0;
}