Cod sursa(job #2538489)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 4 februarie 2020 19:46:19
Problema Ciclu Eulerian Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

const int MAX_N = 100000;
const int MAX_M = 500000;

using namespace std;

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

int n, m;
bool visited[MAX_N + 5]; //node
int sol[MAX_M + MAX_N + 5]; //edge

stack<int> st;
vector<pair<int, int> > G[MAX_N + 5];

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int u, v;
        fin >> u >> v;
        G[u].push_back({v, i});
        G[v].push_back({u, i});
    }

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

        if (visited[i])
            continue;
        st.push(i);

        while (!st.empty()) {
            int u = st.top();
            visited[u] = 1;

            if (G[u].empty())
                st.pop();
            else {
                int v = G[u].back().first;
                int index = G[u].back().second;
                G[u].pop_back();

                if (sol[index])
                    continue;

                sol[index] = 1;
                fout << v << ' ';
                st.push(v);
            }
        }
    }

    return 0;
}