Cod sursa(job #2007513)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 3 august 2017 09:09:16
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
# include <iostream>
# include <fstream>
# include <vector>

using namespace std;

const int MAX_M = 500000;
const int MAX_N = 100000;
pair<int, int> bord[1 + MAX_N];
bool t[1 + MAX_N];

vector<int> f[1 + MAX_N];

bool visited[1 + MAX_N];
int bfs( int n ) {
    int k = 0;
    vector<int> st;
    st.push_back( n );

    while ( st.size() ) {
        int x = st.back();
        st.pop_back();

        if ( !visited[x] ) {
            k ++;
            for ( int l : f[x] ) {
                int y = bord[l].first ^ bord[l].second ^ x;
                if ( !visited[y] )
                    st.push_back( bord[l].first ^ bord[l].second ^ x );
            }
        }
    }

    return k;
}

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

    int n, m;
    fin >> n >> m;

    for ( int i = 1; i <= m; i ++ ) {
        int a, b;
        fin >> a >> b;

        bord[i].first = a;
        bord[i].second = b;

        f[a].push_back( i );
        f[b].push_back( i );
    }

    int i = 1;
    while ( i <= n && f[i].size() % 2 == 0 )
        i ++;

    if ( i <= n || bfs( 1 ) == n )
        fout << -1 << endl;
    else {
        vector<int> st;
        vector<int> ans;
        st.push_back( 1 );
        while ( !st.empty() ) {
            int node = st.back();

            if ( !f[node].empty() ) {
                int e = f[node].back();
                f[node].pop_back();
                if ( !t[e] ) {
                    t[e] = 1;
                    st.push_back( bord[e].first ^ bord[e].second ^ node );
                }
            } else {
                ans.push_back( node );
                st.pop_back();
            }
        }

        for ( int i = 0; i < ans.size() - 1; i ++ )
            fout << ans[i] << ' ';
    }

    return 0;
}