Cod sursa(job #442579)

Utilizator alexandru92alexandru alexandru92 Data 14 aprilie 2010 20:29:12
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 14, 2010, 7:37 PM
 */
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 100000

/*
 * 
 */
using namespace std;
int d[Nmax];
vector< int > S;
vector< int > G[Nmax];
vector< int >::const_iterator it, iend;
inline bool is_connex( int N )
{
    int x, j=1;
    vector< bool > used(N);
    used[0]=true;
    for( S.push_back(0); !S.empty(); )
    {
        x=S.back(); S.pop_back();
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
            if( !used[*it] )
            {
                ++j;
                if( N == j )
                   return true;
                used[*it]=true;
                S.push_back(*it);
            }
    }
    return false;
}
inline void euclid( int x )
{
    int w;
    while( !G[x].empty() )
    {
        w=G[x].back(); G[x].pop_back();
        G[w].erase( find( G[w].begin(), G[w].end(), x ) );
        S.push_back(x);
        x=w;
    }
}
int main(int argc, char** argv)
{
    int N, M, x, y, k=0;
    ifstream in( "ciclueuler.in" );
    in>>N>>M;
    for( ; M; --M )
    {
        in>>x>>y;
        --x, --y;
        G[x].push_back(y);
        G[y].push_back(x);
        if( 0 == d[x]%2 )
            ++k;
        else --k;
        if( 0 == d[y]%2 )
            ++k;
        else --k;
        ++d[x]; ++d[y];
    }
    if(  N != k  || !is_connex(N) )
    {
        ofstream out( "ciclueuler.out" );
        out<<"-1\n";
        return EXIT_SUCCESS;
    }
    ofstream out( "ciclueuler.out" );
    x=0;
    S.clear();
    do
    {
        euclid(x);
        x=S.back(); S.pop_back();
        out<<(x+1)<<' ';
    }while( !S.empty() ); 
    return EXIT_SUCCESS;
}