Cod sursa(job #2509937)

Utilizator xCata02Catalin Brita xCata02 Data 15 decembrie 2019 12:59:35
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>
#define Nmax 100001
#define Mmax 500005
using namespace std;

ifstream fin ("ciclueuler.in") ;
ofstream fout("ciclueuler.out");

#define cin  fin
#define cout fout

struct Muchii
{
    int x;
    int y;
    bool viz = false;
} v[Mmax];

int n, m, a, b;
int frecv[Nmax], vizitat[Nmax];

stack  < int > solutie;
vector < int > g[Nmax];

void read()
{
    cin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        cin >> v[i].x >> v[i].y;

        g[v[i].x].push_back(i);
        g[v[i].y].push_back(i);

        frecv[v[i].x]++;
        frecv[v[i].y]++;
    }
}

bool verifEuler()
{
    for(int i=1; i<=n; i++)
    {
        if(frecv[i] % 2 == 1)
        {
            return false;
        }
    }
    return true;
}

void euler()
{
    int sus, jos, nod;
    solutie.push(1);
    while(!solutie.empty())
    {
        sus = solutie.top();
        if(!g[sus].empty())
        {
            jos = g[sus].back();
            g[sus].pop_back();
            if(v[jos].viz == false)
            {
                if(sus  == v[jos].x)
                {
                    nod = v[jos].y;
                }
                else
                {
                    nod = v[jos].x;
                }
                solutie.push(nod);
                v[jos].viz = true;
            }
        }
        else
        {
            if(solutie.size() > 1)
            {
                cout << sus << " ";
            }
            solutie.pop();
        }
    }
}

int main()
{
    // citire
    read();

    if(verifEuler() == 1)
    {
        euler();
    }
    else
    {
        cout << -1;
    }
}