Cod sursa(job #1715052)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 9 iunie 2016 22:12:34
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include<fstream>
#include<vector>
#include<list>

using namespace std;

ifstream fin( "ciclueuler.in" ); ofstream fout( "ciclueuler.out" );

typedef vector< int > graf;

const int nmax = 1e5;
const int mmax = 5 * nmax;
int n, m;

graf g[ nmax + 1 ];

struct muchie{
    int x, y;
    bool viz;

    muchie() {}
    muchie( int _x, int _y, bool _viz = 0 ) {
        x = _x, y = _y, viz = _viz;
    }

    inline int capat( int nod ) {
        return x + y - nod;
    }
} v[ mmax + 1 ];

list< int > ans;

void adauga( int nod, list< int >::iterator pos ) {
    while ( ( int )g[ nod ].size() ) {
        if ( v[ g[ nod ][ 0 ] ].viz == 1 ) {
            swap( g[ nod ][ 0 ], g[ nod ].back() );
            g[ nod ].pop_back();
            continue;
        }
        int k = v[ g[ nod ][ 0 ] ].capat( nod );
        ans.insert( pos, k );
        v[ g[ nod ][ 0 ] ].viz = 1;
        swap( g[ nod ][ 0 ], g[ nod ].back() );
        g[ nod ].pop_back();
        nod = k;
    }
}
void euler() {
    ans.push_back( 1 );

    for( list< int >::iterator it = ans.begin(); it != ans.end(); ++ it ) {
        list< int >::iterator pos = it;
        ++ pos;
        adauga( *it, pos );
    }
}
int main() {
    fin >> n >> m;
    for( int i = 1; i <= m; ++ i ) {
        int x, y;
        fin >> x >> y;
        v[ i ] = muchie( x, y );
        g[ x ].push_back( i );
        g[ y ].push_back( i );
    }

    int grimp = 0;
    for( int i = 1; i <= n; ++ i ) {
        if ( g[ i ].size() % 2 ) {
            ++ grimp;
        }
    }

    if ( grimp > 0 ) {
        fout << "-1";
    } else {
        euler();
        ans.pop_back();
        if ( ( int )ans.size() != m ) {
            fout << "-1";
        } else {
            for( list< int >::iterator it = ans.begin(); it != ans.end(); ++ it ) {
                fout << *it << " ";
            }
        }
    }
    fout << "\n";
    fin.close();
    fout.close();
    return 0;
}