Cod sursa(job #1966663)

Utilizator mariakKapros Maria mariak Data 15 aprilie 2017 14:37:12
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
/*----Eulerian Cycle/Path
    Eulerian Path is a path in graph that visits every edge exactly once.
            cond : graph is connected + exacly 2 nodes with odd degree
    Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex.
            cond : graph is connected + all nodes have even degree
*/

#include <bits/stdc++.h>
#define maxN 100002
#define pii pair <int, int>
#define mp make_pair

FILE *fin  = freopen("ciclueuler.in", "r", stdin);
FILE *fout = freopen("ciclueuler.out", "w", stdout);

using namespace std;
int N, M;
int gr[maxN];
vector <int> euler;
vector <pii> G[maxN];
bitset <5 * maxN> checked;
stack <int> st;
bool ifCycle;
int no_edge;

int DeleteNext(int node) {
    while(!G[node].empty() && checked.test(G[node].back().second))
        G[node].pop_back();
    pii edge = G[node].back(); G[node].pop_back();
    checked.set(edge.second);
    gr[node] --; gr[edge.first] --;
    return edge.first;
}

void EulerianCycle(){
    ifCycle = true;
    for(int i = 1; i <= N; i ++)
        if(gr[i] & 1){
            ifCycle = false;
            return;
        }
    int start = 1;
    while(start <= N && !gr[start]) start ++;
        st.push(start);

    while(!st.empty()){
        int node = st.top();
        if(gr[node] != 0)
            st.push(DeleteNext(node));
            else{
                euler.push_back(node);
                st.pop();
            }
        }
}

int main(){
    scanf("%d %d", &N, &M);
    for(int i = 1; i <= M; ++ i){
        int x, y;
        scanf("%d %d", &x, &y);
        ++ gr[x], ++ gr[y];
        ++ no_edge;
        G[x].push_back(mp(y, no_edge));
        G[y].push_back(mp(x, no_edge));
    }
    EulerianCycle();
    /*------Output-------*/
    if(!ifCycle)
        printf("-1\n");
    else{
        for(int i = 0; i < (int)euler.size() - 1; i++)
            printf("%d ", euler[i]);
        printf("\n");
    }
    return 0;
}