Cod sursa(job #2176354)

Utilizator vladdy47Bucur Vlad Andrei vladdy47 Data 16 martie 2018 23:15:47
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
# include <bits/stdc++.h>

using namespace std;

const int nmax = 1e5 + 5;

stack <int> st;
vector <int> G[nmax], ans;
pair <int, int> edge[nmax * 5];
int i, n, m, x;
bool sel[nmax * 5];


void ciclu ()
{

    for (i = 1; i <= n; ++i)
        if (G[i].size() % 2)
        {
            printf("-1\n");
            return;
        }
    st.push(1);

    while (st.size())
    {
        int node = st.top();

        if (!G[node].size())
        {
            ans.push_back(node);
            st.pop();
            continue;
        }

        int to = G[node].back(); G[node].pop_back();

        if (!sel[to]) {
            sel[to] = true;
            if (edge[to].first == node) x = edge[to].second;
                else x = edge[to].first;
            st.push(x);
        }
    }

    ans.pop_back();
}

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

    scanf("%d %d\n", &n, &m);

    for (i = 1; i <= m; ++i)
    {
        int x, y;

        scanf("%d %d\n", &x, &y);

        G[x].push_back(i), G[y].push_back(i);

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

    ciclu();

    for (auto &it: ans)
        printf("%d ", it);

    printf("\n");

    return 0;
}