Cod sursa(job #1685887)

Utilizator bogdan10bosBogdan Sitaru bogdan10bos Data 11 aprilie 2016 21:57:48
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

using namespace std;

#define FILE_IO

vector <int> ans, edg[100005];
stack <int> stv;

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

    int N, M;
    scanf("%d%d", &N, &M);
    for(int i = 1; i <= M; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        edg[x].push_back(y);
        edg[y].push_back(x);
    }

    for(int i = 1; i <= N; i++)
        if(edg[i].size() % 2)
        {
            printf("-1");
            return 0;
        }

    int pos = 1;
    while(edg[pos].size() == 0)
        pos++;

    stv.push(pos);
    while(!stv.empty())
    {
        int nod = stv.top();

        if(edg[nod].size() == 0)
        {
            ans.push_back(nod);
            stv.pop();
            continue;
        }

        int nxt = edg[nod][0];
        edg[nod].erase(edg[nod].begin());
        for(auto it = edg[nxt].begin(); it != edg[nxt].end(); it++)
            if( (*it) == nod )
            {
                edg[nxt].erase(it);
                break;
            }
        stv.push(nxt);
    }

    ans.pop_back();
    for(auto it = ans.begin(); it != ans.end(); it++)
        printf("%d ", (*it));

    return 0;
}