Cod sursa(job #1832102)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 19 decembrie 2016 14:10:42
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
using namespace std;

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

const int DIM = 500010;

int r[DIM], ma[DIM];

vector<int> st;
vector<pair<int, int>> g[DIM];

void dfs( int x ) {
    ma[x] = 1;

    for( pair<int, int> y : g[x] ) {
        if( ma[y.first] == 0 )
            dfs( y.first );
    }

    return;
}

int main( void ) {

    int n, m;
    in >> n >> m;

    for( int i = 1; i <= m; i ++ ) {
        int x, y;
        in >> x >> y;

        g[x].push_back( make_pair(y, i) ); r[x] ++;
        g[y].push_back( make_pair(x, i) ); r[y] ++;
    }

    int s = 1;
    while( r[s] == 0 )
        s ++;

    if( s <= n )
        dfs( s );

    if( count( ma + 1, ma + n + 1, 1 ) !=
                 n - count( r + 1, r + n + 1, 0 ) ||
        count_if( r + 1, r + n + 1, [](int x){
                 return x % 2 == 1; } ) != 0 ) {

        out << -1 << endl;
        return 0;
    }

    fill( ma + 1, ma + n + 1, 0 );
    st.push_back( 1 );

    bool ok = false;
    while( !st.empty() ) {
        int x = st.back();

        while( !g[x].empty() && ma[g[x].back().second] == 1 )
            g[x].pop_back();

        if( !g[x].empty() ) {
            pair<int, int> y = g[x].back();

            g[x].pop_back(); ma[y.second] = 1;
            st.push_back( y.first );
        } else {
            if( ok == true )
                out << x << " ";
            else
                ok = true;

            st.pop_back();
        }
    }

    return 0;
}