Cod sursa(job #983105)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 10 august 2013 20:34:08
Problema Ciclu Eulerian Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <stack>

using namespace std;

#define Nmax 100

list<int> G[Nmax];
vector<bool> viz(Nmax);
vector<int> degree(Nmax);

stack<int> Stack;

int N, M, P;

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

void read()
{
    f >> N >> M;

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

        degree[a]++;
        degree[b]++;

        G[a].push_back( b );
        G[b].push_back( a );
    }

    f.close();
}

void DFS( int nod )
{
    viz[nod] = 1;

    for ( list<int>::iterator it = G[nod].begin(); it != G[nod].end(); ++it )
            if ( !viz[ *it ] )
                    DFS( *it );

    P++;
}

bool Check_Eulerian()
{
    DFS( 1 );

    if ( P != N )
            return false;

    for ( int i = 1; i <= N; ++i )
            if ( degree[i] & 1 )
                    return false;

    return true;
}

inline void Euler( int nod )
{
    while( !G[nod].empty() )
    {
        int Y = G[nod].front();
        G[nod].pop_front();

        Stack.push( nod );

        for ( list<int>::iterator it = G[Y].begin(); it != G[Y].end(); ++it )
                if ( *it == nod )
                {
                    G[Y].erase( it );
                    break;
                }

        nod = Y;
    }
}

void Eulerian_Cycle()
{
    int nr = 0;

    Stack.push( 1 );

    do
    {
        int X = Stack.top();
        Stack.pop();
        Euler( X );
        nr++;

        if ( nr != M+1 )
                g << X << " ";

    } while( !Stack.empty() );
}

int main()
{
    read();

    if ( Check_Eulerian() )
    {
        Eulerian_Cycle();
    }
    else
    {
        g << "-1\n";
    }

    g.close();

    return 0;
}