Cod sursa(job #2502415)

Utilizator stefan_creastaStefan Creasta stefan_creasta Data 30 noiembrie 2019 20:05:40
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <cstdio>
#include <vector>
#include <stack>
using namespace std;
const int NMAX = 500005;
struct Muchie {
    int v, nrm;
};
vector <Muchie> g[NMAX];
bool viz[NMAX];
int sol[NMAX];
stack <int> st;

int main() {
    int n, m;
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++) {
        int a, b;
        scanf("%d%d", &a, &b);
        g[a].push_back({b, i});
        g[b].push_back({a, i});
    }
    bool ok = 1;
    for(int i = 1; ok == 1 && i <= n; i++) {
        if(g[i].size() % 2 == 1) {
            ok = 0;
        }
    }
    if(ok == 0) {
        printf("-1\n");
        return 0;
    }
    int top = 0;
    st.push(1);
    while(!st.empty()) {
        int u = st.top();
        while(!g[u].empty() && viz[g[u].back().nrm] == 1) {
            g[u].pop_back();
        }
        if(!g[u].empty()) {
            auto nr = g[u].back();
            viz[nr.nrm] = 1;
            st.push(nr.v);
        }
        else {
            st.pop();
            if(!st.empty()) {
                sol[++top] = st.top();
            }
        }
    }
    for(int i = 1; i <= top; i++) {
        printf("%d ", sol[i]);
    }
    printf("\n");
    return 0;
}