Cod sursa(job #2154762)

Utilizator vazanIonescu Victor Razvan vazan Data 7 martie 2018 11:52:18
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include<cstdio>
using namespace std;

#define NMAX 100100
#define MMAX 1000100

int nxt[MMAX], last[NMAX], val[MMAX], grade[NMAX], cr = 0;
char elim[MMAX];

void add(int a, int b){
    cr++;
    val[cr] = b;
    nxt[cr] = last[a];
    last[a] = cr;
}

int st_e[NMAX];
int rez[MMAX], cc = 1;

int main(){
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++){
        int a, b;
        scanf("%d%d", &a, &b);
        add(a, b);
        add(b, a);
        grade[a]++;
        grade[b]++;
    }
    for(int i = 1; i <= n; i++)
        if(grade[i] & 1){
            printf("-1");
            return 0;
        }
    int st_top = 1;
    st_e[1] = 1;
    while(st_top){
        if(!last[st_e[st_top]]){
            rez[cc] = st_e[st_top];
            cc++;
            st_top--;
        }
        else{
            int cst = st_top;
            if(!elim[last[st_e[st_top]]]){
                int st1 = st_top + 1;
                st_e[st1] = val[last[st_e[st_top]]];
                cst = st1;
                int aux = last[st_e[st_top]];
                elim[aux + ((aux & 1) ? 1 : -1)] = 1;
            }
            last[st_e[st_top]] = nxt[last[st_e[st_top]]];
            st_top = cst;
        }
    }
    for(int i = 1; i < cc - 1; i++){
        printf("%d ", rez[i]);
    }

    return 0;
}