Cod sursa(job #3294603)

Utilizator AnaMateiAna Matei AnaMatei Data 26 aprilie 2025 12:10:11
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>
#include <stack>

using namespace std;

const int NMAX=100001, MMAX=500001;

struct muchie
{
    int nod, nrm;/// nrm=nr de ordine al muchiei
    muchie(int xx=0, int nn=0): nod(xx), nrm(nn) {}
};

int n, m;

vector<muchie> G[NMAX];
vector<int> L;
bitset<MMAX> elim;
stack<int> S;

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

void citire()
{
    int x, y;
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        f>>x>>y;
        G[x].push_back(muchie(y, i));
        G[y].push_back(muchie(x, i));
    }
}

void euler()
{
    int x;
    muchie mm;
    S.push(1);
    while(!S.empty())
    {
        x=S.top();
        if(G[x].size()>0)/// exista muchii incidente cu x
        {
            mm=G[x].back();/// o luam pe ultima din lista
            G[x].pop_back();///o eliminam din lista lui x
            if(!elim[mm.nrm])
            {
                elim[mm.nrm]=1;
                S.push(mm.nod);
            }
        }
        else
        {
            L.push_back(x);
            S.pop();
        }
    }
}

int main()
{
    bool ok=1;
    citire();
    for(int i=1; i<=n && ok; i++)
    {
        if(G[i].size() & 1)/// exista un nod cu grad imapar
            ok=0;
    }
    if(ok)
    {
        euler();
        for(int i=L.size()-1; i>=1; i--)
            g<<L[i]<<' ';
    }
    else
        g<<"-1\n";
    f.close();
    g.close();
    return 0;
}