Cod sursa(job #2007921)

Utilizator EuAlexOtaku Hikikomori EuAlex Data 4 august 2017 15:38:21
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <cstdio>
#include <queue>
#include <vector>
#include <stack>

using namespace std;

struct Muchie{
    int from, to;
    bool del;
};

queue <int> q;
stack <int> st;
vector <int> graf[100005];
Muchie edge[500005];
bool viz[100005];

bool bfs(int n) {
    q.push(1);
    viz[1] = 1;

    while(!q.empty()) {
        int from = q.front(), to;

        for(int i = 0; i < graf[from].size(); ++ i) {
            Muchie aux = edge[graf[from][i]];
            if(from == aux.from) {
                to = aux.to;
            } else {
                to = aux.from;
            }

            if(viz[to] == 0) {
                q.push(to);
                viz[to] = 1;
            }
        }

        q.pop();
    }

    for(int i = 1; i <= n; ++ i) {
        if(graf[i].size() > 0 && viz[i] == 0) {
            return 0;
        }
    }

    return 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 u, v;
        scanf("%d%d", &u, &v);

        edge[i] = {u, v, 0};

        graf[u].push_back(i);
        graf[v].push_back(i);
    }

    for(int i = 1; i <= n; ++ i) {
        if(graf[i].size() % 2 != 0) {
            printf("-1");
            return 0;
        }
    }

    if(bfs(n) == false) {
        printf("-1");
        return 0;
    }

    st.push(1);
    while(!st.empty()) {
        int from = st.top(), to;

        if(graf[from].size() == 0) {
            printf("%d ", from);
            st.pop();
        } else {
            Muchie aux = edge[graf[from].back()];
            if(aux.del == 0) {
                edge[graf[from].back()].del = 1;
                if(from == aux.from) {
                    to = aux.to;
                } else {
                    to = aux.from;
                }

                st.push(to);
            }
            graf[from].pop_back();
        }
    }

    return 0;
}