Cod sursa(job #2083171)

Utilizator netfreeAndrei Muntean netfree Data 7 decembrie 2017 09:30:34
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

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

const int N_MAX = 100000 + 5;
const int M_MAX = 500000 + 5;

int n, m;
bitset<M_MAX> used;
bitset<N_MAX> viz;
int g[N_MAX];
vector<pii> vec[N_MAX];
stack<int> st;
vector<int> ans;

void dfs(int nod) {
    viz[nod] = true;
    for(auto v : vec[nod])
        if(!viz[v.x])
            dfs(v.x);
}

void failure_fucntion(){
    dfs(1);
    for(int i = 1; i<=n; ++i)
        if(!viz[i]){
            fout << -1;
            exit(0);
        }
    for(int i = 1; i<=n; ++i)
        if(g[i] % 2 != 0){
            fout << -1;
            exit(0);
        }
}

void solve(){
    st.push(1);

    while(!st.empty()){

        int nod = st.top();

        if(g[nod] == 0) {
            ans.push_back(nod);
            st.pop();
        }

        else {
            /// din capat, scot tot ce a fost usedosit deja pentru a ajugne la un nou bun
            while(used[vec[nod].back().y])
                vec[nod].pop_back();


            int new_nod = vec[nod].back().x; ///nod bun

            g[nod]--;
            g[new_nod]--;

            used[vec[nod].back().y] = true;

            vec[nod].pop_back();
            st.push(new_nod);
        }
    }

    for(int i = ans.size()-1; i>=1; --i)
        fout << ans[i] << " ";
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int a, b;
        fin >> a >> b;
        vec[a].push_back({b, i});
        vec[b].push_back({a, i});
        g[a]++;
        g[b]++;
    }

    failure_fucntion();

    solve();

    return 0;
}