Cod sursa(job #3194216)

Utilizator lucriLuchian Cristian lucri Data 17 ianuarie 2024 12:14:07
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>
std::ifstream cin("ciclueuler.in");
std::ofstream cout("ciclueuler.out");
std::vector<std::pair<int,int>>a[100010];
std::vector<bool>fol[100010];
int n,m,t[100010],sz[100010],poz[100010],nr,x,y;
bool gr[100010];
inline int tata(int nod)
{
    if(t[nod]==nod) return nod;
    return t[nod]=tata(t[nod]);
}
inline void calculeaza(int nod)
{
    int b;
    std::stack<int>route;
    route.push(nod);
    while(1)
    {
        b=route.top();
        while(poz[b]<sz[b]&&fol[b][poz[b]]==true)
            ++poz[b];
        if(poz[b]==sz[b])
            break;
        fol[b][poz[b]]=true;
        route.push(a[b][poz[b]].first);
        fol[a[b][poz[b]].first][a[b][poz[b]].second]=true;
    }
    b=route.top();
    route.pop();
    while(!route.empty())
    {
        b=route.top();
        if(!a[b].empty())
        {
            cout<<b<<' ';
            calculeaza(route.top());
        }
        else
            cout<<b<<' ';
        route.pop();
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;++i)
        t[i]=i;
    for(int i=1;i<=m;++i)
    {
        cin>>x>>y;
        ++sz[x];
        ++sz[y];
        gr[x]=!gr[x];
        if(gr[x]==true)
            ++nr;
        else
            --nr;;
        gr[y]=!gr[y];
        if(gr[y]==true)
            ++nr;
        else
            --nr;
        if(x!=y)
        {
            a[x].push_back({y,sz[y]-1});
            a[y].push_back({x,sz[x]-1});
            fol[x].push_back(false);
            fol[y].push_back(false);
        }
        else
        {
            a[x].push_back({x,sz[x]-1});
            a[x].push_back({x,sz[x]-2});
            fol[x].push_back(false);
            fol[x].push_back(false);
        }
        t[tata(x)]=tata(y);
    }
    if(nr>0)
    {
        cout<<-1;
        return 0;
    }
    for(int i=1;i<n;++i)
    {
        if(tata(i)!=tata(i+1))
        {
            cout<<-1;
            return 0;
        }
    }
    calculeaza(1);
    return 0;
}