Cod sursa(job #1761967)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 23 septembrie 2016 09:45:29
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

const int NMAX = 1e5 + 1;

int n, m, deg[NMAX];
vector<int> v[NMAX];
vector<int> ans;
bool viz[NMAX];

inline bool evenDegrees() {
    for (int i = 1; i <= n; ++i)
        if (deg[i] % 2)
            return 0;
    return 1;
}

void dfs(int node) {
    viz[node] = 1;
    for (const int& x: v[node])
        if (!viz[x])
            dfs(x);
}

inline bool connected() {
    dfs(1);
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            return 0;
    return 1;
}

inline void buildCycle() {
    stack<int> stk;
    stk.push(1);
    int x, y;
    while (stk.size()) {
        x = stk.top();
        if (v[x].size()) {
            y = v[x].back();
            v[x].pop_back();
            v[y].erase(find(v[y].begin(), v[y].end(), x));
            stk.push(y);
        }
        else {
            ans.push_back(x);
            stk.pop();
        }
    }
}

inline bool eulerianCycle() {
    if (!connected() || !evenDegrees()) {
        return 0;
    }
    buildCycle();
    return 1;
}

inline void writeAns() {
    bool sol = eulerianCycle();
    if (!sol)
        fout << -1;
    else {
        ans.pop_back();
        for (const int& x: ans)
            fout << x << ' ';
    }
}

int main()
{
    fin >> n >> m;
    for (int x, y; m; --m) {
        fin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
        ++deg[x];
        ++deg[y];
    }
    writeAns();
    return 0;
}