Cod sursa(job #1227785)

Utilizator SagunistuStrimbu Alexandru Sagunistu Data 11 septembrie 2014 17:45:43
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.43 kb
#include <iostream>
#include <fstream>
#include <stack>

using namespace std;

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

struct nod
{
    int inf;
    nod *urm;
};

int n,m,nrv[100010];
nod *l[100010];
bool s[100010];
stack <int> st;

void citire()
{
    fin>>n>>m;
    nod *p;
    int x,y;
    for(int i=1;i<=m;i++)
    {
        fin>>x>>y;
        p=new nod;
        p->inf=x;
        p->urm=l[y];
        l[y]=p;
        nrv[x]++;
        p=new nod;
        p->inf=y;
        p->urm=l[x];
        l[x]=p;
        nrv[y]++;
    }
}

void dfs(int k)
{
    s[k]=1;
    st.push(k);
    int nr;
    while(!st.empty())
    {
        while(1)
        {
            nod *p;
            nr=st.top();
            for(p=l[nr];p;p=p->urm)
            {
                if(s[p->inf]==0)
                {
                    s[p->inf]=1;
                    st.push(p->inf);
                    break;
                }
            }
            if(p==0)
                break;
        }
        st.pop();
    }
}

bool conex()
{
    dfs(1);
    for(int i=1;i<=n;i++)
        if(s[i]==0)
            return 0;
    return 1;
}

bool grad_par()
{
    for(int i=1;i<=n;i++)
        if(nrv[i]%2==1)
            return 0;
    return 1;
}

void ciclu()
{
    st.push(1);
    int nodc=1,nodv;
    nod *p,*q;
    while(!st.empty())
    {
        while(nrv[nodc]!=0)
        {
            nodv=nodc;
            nrv[nodc]--;
            p=l[nodc];
            l[nodc]=l[nodc]->urm;
            nodc=p->inf;
            nrv[nodc]--;
            st.push(nodc);
            delete p;
            p=l[nodc];
            if(p->inf==nodv)
            {
                q=p;
                p=p->urm;
                delete q;
                l[nodc]=p;
            }
            else
            {
                while(p->urm->inf!=nodv)
                    p=p->urm;
                q=p->urm;
                p->urm=p->urm->urm;
                delete q;
            }
        }
        while(nrv[nodc]==0&&!st.empty())
        {
            if(st.size()>1)
            fout<<nodc<<" ";
            st.pop();
            if(!st.empty())
            {
                nodc=st.top();
            }
        }
    }
}

int main()
{
    citire();
    if(conex()&&grad_par())
    {
        ciclu();
    }
    else
        fout<<-1;
    return 0;
}