Cod sursa(job #2323192)

Utilizator tnocNume corect tnoc Data 18 ianuarie 2019 22:13:58
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#define NMAX 100010
#define MMAX 500010

using namespace std;

int n, m, sterse;
int nodviz[NMAX];
vector<int> v[NMAX], sol;
int stiv[MMAX], st;



void citire()
{
    scanf("%d %d", &n, &m);
    int t1, t2;
    for (int i = 1; i <= m; i++)
    {
        scanf("%d %d", &t1, &t2);
        v[t1].push_back(t2);
        v[t2].push_back(t1);
    }
}

void euler()
{
    for (int i = 1; i <= n; i++)
        if (v[i].size()%2)
    {
         printf("-1");
            return;
    }
    stiv[++st] = 1;
    while (st > 0)
    {
        int top = stiv[st];

        if (v[top].size() == 0)
        {
            sol.push_back(top);
            nodviz[top]++;
            st--;
            continue;
        }
        int next = v[top][0];
        v[top].erase(v[top].begin());
        sterse++;
        for (int i = 0; i < v[next].size(); i++)
            if (v[next][i] == top)
            {
                v[next].erase(v[next].begin()+i);
                break;
            }
        stiv[++st] = next;
    }
    for (int i = 1; i <= n; i++)
        if (nodviz[i] == 0)
        {
            printf("-1");
            return;
        }
    if (sterse != m)
    {
        printf("-1");
        return ;
    }
    for (int i = sol.size()-1; i > 0; i--)
        printf("%d ", sol[i]);
}

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

    citire();
    euler();

    return 0;
}