Cod sursa(job #1526808)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 17 noiembrie 2015 12:57:35
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
/**
  *  Worg
  */
#include <stack>
#include <cstdio>
#include <vector>

#define pb          push_back

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

const int MAX_N = 1 + 100000,
          MAX_M = 1 + 500000;

struct edge {

    int index, vertex;
    edge(const int &index, const int &vertex) {

        this->index = index;
        this->vertex = vertex;
    }
};

stack < int > stiva;
vector < int > sol;
vector < edge > G[MAX_N];

bool checked[MAX_M];
bool possible;
int degree[MAX_N];
int M;

void addEdge(const int &u, const int &v) {

    degree[u]++;
    degree[v]++;
    G[u].pb(edge(M, v));
    G[v].pb(edge(M, u));
    M++;
}

int deleteNext(int node) {

    while(!G[node].empty() && checked[G[node].back().index])
        G[node].pop_back();

    if(!G[node].empty()) {

        checked[G[node].back().index] = true;
        int nxt = G[node].back().vertex;
        G[node].pop_back();

        M--; degree[node]--; degree[nxt]--;
        return nxt;
    }
    else {

        return 0;
    }
}

int main() {

    int n, m;
    scanf("%d %d ", &n, &m);
    for(int i = 1; i <= m; ++i) {

        int u, v;
        scanf("%d %d ", &u, &v);
        addEdge(u, v);
    }
    possible = true;
    for(int i = 1; i <= n; ++i)
        if(degree[i] % 2 == 1)
            possible = false;

    if(possible) {

        int i;
        for(i = 1; !degree[i]; ++i);
        stiva.push(i);

        while(!stiva.empty()) {

            int node = stiva.top();
            if(degree[node])    /* daca nodul mai are vecini, continuam cu urmatorul */
                stiva.push(deleteNext(node));
            else {              /* altfel, il adaugam la solutie si il eliminam din stiva */

                sol.pb(node);
                stiva.pop();
            }
        }
        if(M > 0)
            possible = false;
    }

    if(possible) {

        for(int i = 0; i < (int)sol.size() - 1; ++i) {

            printf("%d ", sol[i]);
        }
        printf("\n");
    }

    else {

        printf("-1\n");
    }
    return 0;

}