Cod sursa(job #872375)

Utilizator lucian666Vasilut Lucian lucian666 Data 5 februarie 2013 23:34:48
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb



#include<fstream>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<algorithm>


#define NN 100001
#define po pop_back
#define pb push_back

using namespace std;
ofstream out("ciclueuler.out");

int n , m , gr[NN] ;

vector < int > G[NN] , sol  ;
typedef vector < int >:: iterator IT;

queue <int> Q;

bitset< NN > uz;

stack < int > S;


void read();
void BFS( int );
void sterge( int x ,int y);
inline int conex();
void euler( int start);
void wrt();


int main()
{
    read();
    wrt();
    return 0;
}

void read()
{
    ifstream in("ciclueuler.in");

    in >> n >> m;

    for ( int x , y ; m ; --m )
    {
        in >> x >> y;
        G[x].pb(y);
        G[y].pb(x);

        ++gr[x];
        ++gr[y];
    }

}

void BFS( int start )
{
    uz[ start] = 1;
    Q.push( start );
        while( !Q.empty() )
        {
            int k = Q.front();
                for ( IT I = G[k].begin(); I!=G[k].end(); ++I)
                    if ( !uz[ *I ] )
                    {
                        uz[ *I ] = 1;
                        Q.push( *I );
                    }
                    Q.pop();
        }
}

inline int conex()
{
    for ( int i = 1 ; i<=n;i++)
        if  ( gr[i] % 2 == 1 )
            return 0;

    BFS( 1 );
        for ( int i=1 ;i<=n;i++)
            if ( !uz[i] )
                return 0;

        return 1;
}


void sterge( int start , int sursa )
{
    G[start].po();
        for ( IT I = G[sursa].begin(); I!=G[sursa].end(); ++I)
            if ( *I == start)
            {
                G[sursa].erase(I);
                break;
            }
}

void euler( int start )
{
    int nod;
        while( !G[start].empty() )
        {

            nod = G[start].back();

            S.push( start );

            sterge( start , nod );

            start = nod;
        }
}





void wrt()
{


    if ( conex() )
    {
     int   start = 1;

        do
        {
            euler(start);
            start = S.top();
            S.pop();
            sol.pb( start );

        }
        while( !S.empty() );

        reverse(sol.begin(),sol.end() );
        for ( int i = 0; i<sol.size(); ++i)
            out << sol[i] << " ";
    }
    else
        out << -1;




}