Cod sursa(job #1918225)

Utilizator B_RazvanBaboiu Razvan B_Razvan Data 9 martie 2017 14:35:25
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#define NMAX 100005

using namespace std;

int n, m, viz[5*NMAX], solutie[NMAX], k;
vector <pair <int, int> > g[NMAX];
vector <pair <int, int> >::iterator it;
stack <int> s;

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

void euler()
{
    int nod;
    s.push(1);
    int indiceMuchie, fiu;
    while(!s.empty())
    {
        nod=s.top();
        if(!g[nod].empty())
        {
            indiceMuchie=g[nod].back().second;
            fiu=g[nod].back().first;
            g[nod].pop_back();
            if(viz[indiceMuchie]==0)
            {
                viz[indiceMuchie]=1;
                s.push(fiu);
            }
        }
        else
        {
            s.pop();
            solutie[k++]=nod;
        }
    }
}

int verificareEuler()
{
    for(int i=1; i<=n; ++i)
        if(g[i].size()%2)
            return 0;
    return 1;
}

void afisare()
{
    for(int i=0; i<=k-2; ++i)
        printf("%d ", solutie[i]);
}

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