Cod sursa(job #670638)

Utilizator psycho21rAbabab psycho21r Data 29 ianuarie 2012 17:47:16
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
//stafida
#include <fstream>
#include <list>
#include <stack>

using namespace std;

list<int> e[100001], cycle;
int n, m;

list<int> find_cycle(int st_ver)
{
    int now = st_ver, back;
    list <int> cycle;
    cycle.push_back(now);
    do
    {
        back = now;
        now = e[now].back();
        e[back].pop_back();
        list<int>::iterator it;
        for(list<int>::iterator it=e[now].begin(); it!=e[now].end(); ++it)
            if(*it==back)
            {
                e[now].erase(it);
                break;
            }
        cycle.push_back(now);
    }
    while(now!=st_ver);
    return cycle;
}

int main()
{
    ifstream in("ciclueuler.in");
    in >> n >> m;
    for(int a, b, i = 0; i < m; ++i)
    {
        in >> a >> b;
        e[a].push_back(b);
        e[b].push_back(a);
    }
    in.close();
    ofstream out("ciclueuler.out");
    for(int i = 1; i <= n; ++i)
    {
        if(e[i].size() & 1)
        {
            out << "-1";
            return 0;
        }
    }
    /*----------ALGORITHM----------*/
    stack <int> sol, back_sol;
    int now = 1;
    list<int>::iterator nw;
    bool k;
    do
    {
        list<int> cycle = find_cycle(now);
        k = false;
        for(list<int>::iterator it=cycle.begin(); it!=cycle.end(); ++it)
        {
            sol.push(*it);
            if(e[*it].size()>0)
            {
                now = *it;
                nw = it;
                k = true;
                break;
            }
        }
        if (k)
        for(list<int>::iterator it=cycle.end(); it!=nw; --it)
            back_sol.push(*it);

    }
    while(k);
    while(!back_sol.empty())
    {
        sol.push(back_sol.top());
        back_sol.pop();
    }
    int show = 1;
    sol.pop();
    while(!sol.empty())
    {
        out << show << " ";
        show = sol.top();
        sol.pop();
    }
    out.close();
    /*-----------------------------*/
    return 0;
}