Cod sursa(job #2188841)

Utilizator valentinoMoldovan Rares valentino Data 27 martie 2018 15:15:54
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");

const int NMax = 100001;

stack < int > stiva;
vector < pair < int, int > > graf[NMax];
int n, m, used[NMax * 5];

int main()
{
    int x, y;
    vector < int > cycle;
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y;
        graf[x].push_back({y, i});
        graf[y].push_back({x, i});
    }

    for(int i = 1; i <= n; ++i)
        if((graf[i].size() & 1) || !graf[i].size())
    {
        g << -1 << '\n';
        return 0;
    }

    stiva.push(1);
    while(!stiva.empty())
    {
        int node = stiva.top();

        if(graf[node].size())
        {
            if(!used[ graf[node].back().second ])
            {
                used[graf[node].back().second] = 1;
                stiva.push(graf[node].back().first);

            }
            graf[node].pop_back();
        }
        else
            {
                cycle.push_back(node);
                stiva.pop();
            }
    }
    for(int i = 0; i < cycle.size() - 1; ++i)
        g << cycle[i] << ' ';
}