Cod sursa(job #797654)

Utilizator tzipleatudTudor Tiplea tzipleatud Data 14 octombrie 2012 16:13:58
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <stack>
#include <vector>
#define NM 100010
#define MM 500010
#define PI pair<int, int>
#define nd first
#define in second

using namespace std;

ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");

vector<PI> G[NM];

bool F[MM];
int N,M,i,j,a,b;
stack<int> S;
stack<PI> ST;
int DG[NM];
bool V[NM];

void DF (int nod)
{
    V[nod]=1;

    for (vector<PI>::iterator it=G[nod].begin(); it!=G[nod].end(); ++it)
        if (!V[it->nd])
            DF(it->nd);
}

bool Ok ()
{
    DF(1);
    for (i=1; i<=N; i++)
        if ((V[i]==0 && G[i].size()!=0) || DG[i]%2==1)
            return 0;
    return 1;
}

void Euler ()
{
    ST.push(make_pair(1,-1));

    while (!ST.empty())
    {
        i=ST.top().first;
        j=ST.top().second;
        ST.pop();

        ++j;
        if (j<G[i].size())
        {
            ST.push(make_pair(i,j));
            if (F[G[i][j].in]==0)
            {
                F[G[i][j].in]=1;
                ST.push(make_pair(G[i][j].nd,-1));
            }
        }
        else
            S.push(i);
    }
}

int main ()
{
    f >> N >> M;
    for (i=1; i<=M; i++)
    {
        f >> a >> b;

        DG[a]++;
        DG[b]++;
        G[a].push_back(make_pair(b,i));
        G[b].push_back(make_pair(a,i));
    }

    if (!Ok())
    {
        g << -1 << '\n';

        f.close();
        g.close();
        return 0;
    }

    Euler();

    while (S.size()>=2)
    {
        g << S.top() << ' ';
        S.pop();
    }

    g << '\n';
    f.close();
    g.close();
    return 0;
}