Cod sursa(job #903218)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 1 martie 2013 19:13:38
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <cstdio>
#include <cstring>
#include <cassert>

#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <deque>
#include <map>

#define v first
#define e second

using namespace std;

typedef long long LL;
typedef pair<int, int> Edge;
typedef vector<Edge>::iterator it;

const int oo = 0x3f3f3f3f;
const int MAX_N = 100005;
const int MAX_E = 500005;

vector<Edge> G[MAX_N];
int N, E, Degree[MAX_N];
stack<Edge> Stack;
deque<Edge> Cycle;
bool Used[MAX_E], Solution;

inline int GetDegree(int X) {
    for (; Degree[X] > 0 && Used[G[X][Degree[X] - 1].e]; --Degree[X]);
    return Degree[X];
}

inline int Euler(int X) {
    for (int Y; GetDegree(X) > 0; X = Y) {
        Y = G[X][Degree[X] - 1].v;
        Used[G[X][Degree[X] - 1].e] = true;
        Stack.push(Edge(X, G[X][Degree[X] - 1].e));
    }
    return X;
}

void EulerianCycle(int Source) {
    int X = Source;
    do {
        Euler(X);
        X = Stack.top().v;
        Cycle.push_front(Stack.top());
        Stack.pop();
    } while (!Stack.empty());
}

bool EulerianGraph() {
    for (int X = 1; X <= N; ++X)
        if (Degree[X] % 2 == 1)
            return false;
    return true;
}

void Solve() {
    Solution = true;
    if (!EulerianGraph()) {
        Solution = false;
        return;
    }
    EulerianCycle(1);
    if (Cycle.size() < E)
        Solution = false;
}

inline void AddEdge(int X, int Y, int Index) {
    G[X].push_back(Edge(Y, Index)); ++Degree[X];
    G[Y].push_back(Edge(X, Index)); ++Degree[Y];
}

void Read() {
    assert(freopen("ciclueuler.in", "r", stdin));
    assert(scanf("%d %d", &N, &E) == 2);
    for (int i = 1; i <= E; ++i) {
        int X, Y; assert(scanf("%d %d", &X, &Y) == 2);
        AddEdge(X, Y, i);
    }
}

void Print() {
    assert(freopen("ciclueuler.out", "w", stdout));
    if (!Solution) {
        printf("-1\n");
        return;
    }
    for (size_t i = 0; i < Cycle.size(); ++i)
        printf("%d ", Cycle[i].v);
}

int main() {
    Read();
    Solve();
    Print();
    return 0;
}