Cod sursa(job #2460648)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 24 septembrie 2019 08:50:44
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#define pb push_back

using namespace std;

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

const int MAXN = 1e5, MAXM = 5 * 1e5;
vector<int> edges[MAXN + 1];
stack<int> st;
vector<int> result;
int e1[MAXM], e2[MAXM], grades[MAXN + 1], n, m, k;
bool used[MAXM];

void read() {
    int x, y;
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y;
        e1[i] = x;
        e2[i] = y;
        edges[x].pb(i);
        edges[y].pb(i);
        ++grades[x];
        ++grades[y];
    }
}

bool isEuler() {
    for (int i = 1; i <= n; ++i)
        if (grades[i] % 2)
            return false;
    return true;
}

void solve() {
    st.push(1);
    while (!st.empty()) {
        int node = st.top();
        if (edges[node].size()) {
            int edge = edges[node].back();
            edges[node].pop_back();
            if (!used[edge]) {
                int to;
                used[edge] = true;
                if (e1[edge] == node)
                    to = e2[edge];
                else
                    to = e1[edge];
                st.push(to);
            }
        }
        else {
            st.pop();
            result.pb(node);
        }
    }
}

int main() {
    read();
    if (isEuler()) {
        solve();
        for (auto &it: result)
            fout << it << ' ';
    }
    else
        fout << -1 << '\n';
    return 0;
}