Cod sursa(job #2123807)

Utilizator B_RazvanBaboiu Razvan B_Razvan Data 6 februarie 2018 17:29:19
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#define NMAX 100005

using namespace std;

int N, M;
bool viz[NMAX];
vector <pair <int, int> > G[NMAX];
vector <pair <int, int> >::iterator it;
stack <int> s;

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

bool checkEuler()
{
    for(int i=1; i<=N; ++i)
        if(G[i].size() % 2)
            return false;
    return true;
}

void euler()
{
    s.push(1);
    int nod, indiceMuchie, vecin;
    while(!s.empty())
    {
        nod = s.top();
        if(!G[nod].empty())
        {
            indiceMuchie = G[nod].back().second;
            vecin = G[nod].back().first;
            G[nod].pop_back();
            if(viz[indiceMuchie] == false)
            {
                viz[indiceMuchie] = true;
                s.push(vecin);
            }
        }
        else
        {
            s.pop();
            printf("%d ", nod);
        }
    }
}

int main()
{
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    read();
    if(checkEuler())
        euler();
    else
        printf("-1");
    return 0;
}