Cod sursa(job #1647100)

Utilizator andrew_assassin789Andrei Manea andrew_assassin789 Data 10 martie 2016 19:00:50
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <stack>
#include <list>
#define w 100001
using namespace std;
stack <unsigned int> st;
list <unsigned> a[w];
list <unsigned> l;
bool viz[w];
bool th(int n)
{
    int i,x;bool ok;
    list <unsigned int>::iterator it;
    st.push(1);viz[1]=1;
    while (!st.empty())
    {
        x=st.top();st.pop();ok=1;
        for (it=a[x].begin();it!=a[x].end()&&ok;it++)
        {
            if (!viz[*it])
            {
                st.push(*it);ok=0;viz[*it]=1;
            }
        }
    }
    for (i=1;i<=n;i++)
        if ((a[i].size()%2)||(!viz[i])) return 0;
    return 1;
}
void sterg(unsigned int x,unsigned int y)
{
    list<unsigned int>::iterator it;
    a[x].pop_front();
    for (it=a[y].begin();*it!=x;it++);
    a[y].erase(it);
}
void cicl(int x)
{
    int y=x,z;bool ok=1;
    while (ok)
    {
        if (!a[y].size()) ok=0;
        else
        {
            st.push(y);
            z=y;
            y=a[y].front();
            sterg(z,y);
        }
    }
}
int main()
{
    ifstream f("ciclueuler.in");
    ofstream g("ciclueuler.out");
    int n,m,i,x,y;
    f>>n>>m;
    for (i=1;i<=m;i++)
    {
        f>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    if (!th(n))
    {
        g<<"-1\n";
    }
    else
    {
        cicl(1);
        while (!st.empty())
        {
            x=st.top();st.pop();
            l.push_front(x);
            cicl(x);
        }
        list <unsigned int>::iterator it;
        for (it=l.begin();it!=l.end();it++)
            g<<*it<<' ';
        g<<'\n';
    }
    f.close();
    g.close();
    return 0;
}