Cod sursa(job #2575962)

Utilizator robx12lnLinca Robert robx12ln Data 6 martie 2020 16:29:18
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include<bits/stdc++.h>
using namespace std;

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

const int DIM = 1e5 + 5;

int N, M, g[DIM], cc, st_nod;
bool f[5 * DIM];
vector< pair<int,int> > edge[DIM];
vector<int> ans, st;

void dfs( int nod ){
    f[nod] = true;
    for( auto v : edge[nod] )
        if( f[ v.first ] == false  )
            dfs( v.first );
}

int main(){
    fin >> N >> M;
    for( int i = 1; i <= M; i++ ){
        int x, y; fin >> x >> y;
        edge[x].push_back( {y, i} );
        edge[y].push_back( {x, i} );
        g[x]++; g[y]++;
    }

    for( int i = 1; i <= N; i++ )
        if( g[i] != 0 && f[i] == false )
            dfs(i), cc++, st_nod = i;

    if( cc > 1 ){
        fout << "-1\n";
        return 0;
    }
    for( int i = 1; i <= N; i++ ){
        if( g[i] % 2 == 1 ){
            fout << "-1\n";
            return 0;
        }
    }

    memset( f, false, sizeof(f) );

    st.push_back( st_nod );
    while( !st.empty() ){
        int nod = st.back();
        if( g[nod] == 0 ){
            st.pop_back();
            ans.push_back( nod );
            continue;
        }
        while( !edge[nod].empty() && f[ edge[nod].back().second ] == true )
            edge[nod].pop_back();
        f[ edge[nod].back().second ] = true;
        st.push_back( edge[nod].back().first );
        g[nod]--;
        g[ edge[nod].back().first ]--;
    }

    ans.pop_back();
    for( int i = 0; i < ans.size(); i++ )
        fout << ans[i] << " ";
    return 0;
}