Cod sursa(job #2374123)

Utilizator victorv88Veltan Victor victorv88 Data 7 martie 2019 17:03:46
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
#define pb push_back
using namespace std;

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

int n, m, st, fn;

stack<int>s;

bitset<500005>viz;

vector<int>graph[100005];
vector<int>rez;
vector<pair<int,int> >muchii;

bool ok=true;

void euler(int ind)
{
    s.push(ind);
    while (!s.empty())
    {
        int nod=s.top();
        if (!graph[nod].size())
        {
            rez.push_back(nod);
            s.pop();
        }
        else
        {
            int ultim=graph[nod].back();
            if (!viz[ultim])
            {
                pair<int,int>muchie=muchii[ultim];
                viz[ultim]=true;
                if (muchie.first!=nod)
                {
                    s.push(muchie.first);
                }
                else
                {
                    s.push(muchie.second);
                }
            }
             graph[nod].pop_back();
        }
    }
}

void verificare()
{
    for (int i=1; i<=n; ++i)
    {
        if (graph[i].size()%2==1)
        {
            g << -1;
            ok=false;
            return;
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i=0; i<m; ++i)
    {
        f >> st >> fn;
        muchii.pb({st,fn});
        graph[st].pb(i);
        graph[fn].pb(i);
    }
    verificare();
    if (ok){
    euler(1);
    int lung=rez.size();
    for (int i=0; i<lung-1; ++i)
    {
        g << rez[i] <<' ';
    }
    }
    return 0;
}