Cod sursa(job #1151145)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 23 martie 2014 21:20:06
Problema Ciclu Eulerian Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#define Nmax 50009
#define oo 2000000000
using namespace std;
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");

int N,M;
vector < int > G[Nmax],Cycle;
stack < int > st;

inline int IsEulerian()
{
    for(int i=1;i<=N;++i)
        if(G[i].size()&1)return 0;
    return 1;
}

inline void Euler(int S)
{
    for(st.push(S); !st.empty(); )
    {
        int node= st.top();
        if(G[node].size())
        {
            int last = G[node].back();
            st.push(last);
            G[node].pop_back();
            G[last].erase(find(G[last].begin(), G[last].end() , node));
        }
        else
        {
            st.pop();
            if(node)Cycle.push_back(node);
            else
                if(Cycle.size())
                {
                    g<<Cycle.size()<<' ';
                    for(vector<int> :: iterator it = Cycle.begin(), fin = Cycle.end() ; it != fin ; ++ it)
                        g << *it << " ";
                    g << "\n";
                    Cycle.clear();
            }
        }
    }
}

int main()
{
    f>>N>>M;
    for(int i=1;i<=M;++i)
    {
        int x,y;
        f>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    if(IsEulerian())
    {
        for(int i=1;i<=N;++i)
            if(G[i].size()&1)
                G[i].push_back(0), G[0].push_back(i);
        Euler(1);
        for(vector< int > ::iterator it=Cycle.begin();it!=Cycle.end();++it)
            g<<*it<<' ';
        g<<'\n';
    }
    else g<<-1<<'\n';
    f.close();
    g.close();
    return 0;
}