Cod sursa(job #2819192)

Utilizator Bogdan.paun50Mandresi Bogdan Bogdan.paun50 Data 18 decembrie 2021 06:13:57
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>

using namespace std;

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

const int DIM = 100005;
int idx_muchie = 0;
vector<pair<int, int>> g[DIM];
bool deleted[5 * DIM];

vector<int> sol;

int grad[DIM];
bool vis[5 * DIM];
int nr_muchii = 0;

void dfs(int nod) {
    vis[nod] = true;
    nr_muchii += (int)g[nod].size();
    for (pair<int, int> e : g[nod]) {
        if (!vis[e.first]) {
            dfs(e.first);
        }
    }
}

void euler(int nod) {
    for (int i = g[nod].size() - 1; i >= 0; --i) {
        int vecin = g[nod][i].first;
        int muchie = g[nod][i].second;
        g[nod].pop_back();
        if (!deleted[muchie]) {
            deleted[muchie] = true;
            euler(vecin);
        }
    }
    sol.push_back(nod);
}

void euler_stiva(int sursa) {
    stack<int> st;
    st.push(sursa);

    while (!st.empty()) {
        int nod = st.top();
        while (!g[nod].empty()) {
            pair<int, int> e = g[nod].back();
            if (!deleted[e.second]) break;
            g[nod].pop_back();
        }

        if (!g[nod].empty()) {
            st.push(g[nod].back().first);
            deleted[g[nod].back().second] = true;
            g[nod].pop_back();
        } else {
            sol.push_back(nod);
            st.pop();
        }
    }
}

int main() {
    int N, M;
    fin >> N >> M;
    for (int i = 1; i <= M; ++i) {
        int x, y;
        fin >> x >> y;
        idx_muchie++;
        g[x].push_back(make_pair(y, idx_muchie));
        g[y].push_back(make_pair(x, idx_muchie));

        grad[x]++;
        grad[y]++;
    }

    for (int i = 1; i <= N; ++i) {
        if (grad[i] % 2 == 1) {
            fout << "-1" << '\n';
            return 0;
        }
    }

    int sursa = 1;
    while (grad[sursa] == 0) sursa++;

    dfs(sursa);
    if (nr_muchii != 2 * M) {
        fout << "-1" << '\n';
        return 0;
    }

    euler_stiva(sursa);

    sol.pop_back();
    for (int x : sol) {
        fout << x << " ";
    }
    fout << '\n';
}