Cod sursa(job #1919492)

Utilizator tudormaximTudor Maxim tudormaxim Data 9 martie 2017 19:47:07
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <cstring>
#include <algorithm>
using namespace std;

ifstream f ("ciclueuler.in");
ofstream fout ("ciclueuler.out");

const int maxn = 1e5 + 5;
vector <int> G[maxn];

class Scanner {
private:
    char Buff[1 << 17];
    int i = (1 << 17) - 1;
    void Advance () {
        if (++i == (1 << 17)) {
            i = 0;
            f.read(Buff, 1 << 17);
        }
    }
public:
    inline Scanner& operator >> (int &val) {
        while (!isdigit(Buff[i])) Advance();
        val = 0;
        while (isdigit(Buff[i])) {
            val = (val << 1) + (val << 3) + (Buff[i] - '0');
            Advance();
        }
        return *this;
    }
} fin ;

bool Is_Euler (int n) {
    for (int  i = 1; i <= n; i++) {
        if (G[i].size() & 1) return false;
    }
    return true;
}

void Euler () {
    stack <int> Stk;
    int node, son;
    Stk.push(1);
    while (!Stk.empty()) {
        node = Stk.top();
        if (G[node].empty()) {
            fout << node << " ";
            Stk.pop();
        } else {
            son = G[node][0];
            G[node].erase(G[node].begin());
            G[son].erase(find(G[son].begin(), G[son].end(), node));
            Stk.push(son);
        }
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, i;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    if (!Is_Euler(n)) {
        fout << "-1\n";
    } else {
        Euler();
        fout << "\n";
    }
    f.close();
    fout.close();
    return 0;
}