Cod sursa(job #1814092)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 23 noiembrie 2016 17:33:12
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 1e5 + 10;
const int mmax = 5e5 + 10;

int n, m;
vector < int > ans, g[nmax];

pair < int, int > edge[mmax];

void input() {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int x, y;
        scanf("%d %d", &x, &y);

        g[x].push_back(i);
        g[y].push_back(i);

        edge[i] = {x, y};
    }
}

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

    bool used[mmax]; int last = 0, s[mmax];
    s[++last] = 1;

    while (last) {
        int node = s[last];

        if ((int)g[node].size() == 0)
             last--, ans.push_back(node);
        else {
            int act = g[node].back();
            g[node].pop_back();

            if (used[act]) continue;

            used[act] = 1;
            s[++last] = (node == edge[act].first) ? edge[act].second : edge[act].first;
        }
    }

    ans.pop_back();
}

void output() {
    for (auto &it : ans) printf("%d ", it);
}

int main()
{
    freopen("ciclueuler.in","r",stdin);
    freopen("ciclueuler.out","w",stdout);

    input();
    solve();
    output();

    return 0;
}