Cod sursa(job #392129)

Utilizator alexandru92alexandru alexandru92 Data 6 februarie 2010 19:44:07
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on February 6, 2010, 6:59 PM
 */
#include <list>
#include <vector>
#include <fstream>
#include <iterator>

/*
 *
 */
using namespace std;
vector< int > d, stack, cycle;
vector< list< int > > v;
list< int >::iterator it, iend;
bool not_connex( void )
{
    int i, j=1, N=d.size();
    vector< bool > uz( N );
    uz[0]=true;
    stack.push_back(0);
    while( !stack.empty() )
    {
        i=stack.back(); stack.pop_back();
        for( it=v[i].begin(), iend=v[i].end(); it != iend; ++it )
            if( !uz[*it] )
            {++j;
                uz[*it]=true;
                stack.push_back(*it);
                if( j == N )
                {stack.clear();
                    return false;
                }
            }
    }
    return true;
}
void euler( int x )
{int w;
    while( !v[x].empty() )
    {
        w=v[x].front();
        v[x].pop_front();
        for( it=v[w].begin(), iend=v[w].end(); it != iend && x != *it; ++it );
        if( it !=iend && x == *it )
            v[w].erase(it);
        stack.push_back(x);
        x=w;
    }
}
int main( void )
{
    int n, m, x, y;
    ifstream in("ciclueuler.in");
    in>>n>>m;
    v.resize(n);
    d.resize(n);
    for( ; m; --m )
    {
        in>>x>>y;
        x-=1; y-=1;
        v[x].push_back(y);
        v[y].push_back(x);
        ++d[x]; ++d[y];
    }
    for( x=0; x < n; ++x )
        if( d[x]%2 )
        {
            ofstream out("ciclueuler.out");
            out<<-1;
            return 0;
        }
    if( not_connex()  )
    {
        ofstream out( "ciclueuler.out" );
        out<<-1;
        return 0;
    }
    x=0;
    do
    {
        euler( x );
        x=stack.back(); stack.pop_back();
        cycle.push_back(x+1);
    }while( !stack.empty() );
    ofstream out("ciclueuler.out");
    copy( cycle.rbegin(), cycle.rend(), ostream_iterator<int>(out, " ") );
    return 0;
}