Cod sursa(job #1969579)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 18 aprilie 2017 15:36:06
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;

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

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

int used[mmax];
pair < int, int > edge[mmax];

vector < int > ans;

void impossible() {
    printf("-1\n");
    exit(0);
}

int second_node(int idx, int node) {
    return (edge[idx].first == node) ? edge[idx].second : edge[idx].first;
}

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

    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};
    }

    for (int i = 1; i <= n; ++i)
        if (g[i].size()&1)
            impossible();

    vector < int > st; st.push_back(1);
    while (st.size()) {
        int node = st.back();

        if (g[node].size() == 0) {
            ans.push_back(node);
            st.pop_back();
        }
        else {
            int to_edge = g[node].back(); g[node].pop_back();
            if (used[to_edge]) continue;

            used[to_edge] = 1;
            int to = second_node(to_edge, to);
            st.push_back(to);
        }
    }

    ans.pop_back();
    for (auto &it: ans)
        printf("%d ", it);
    printf("\n");

    return 0;
}