Cod sursa(job #1884813)

Utilizator roxannemafteiuMafteiu-Scai Roxana roxannemafteiu Data 19 februarie 2017 12:00:36
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 1e5 + 5;

int n, m;
vector <int> graph[N_MAX];
bitset <N_MAX> visited;
stack <int> st;

void read() {
    ifstream fin("ciclueuler.in");

    fin >> n >> m;
    while (m--) {
        int a, b;
        fin >> a >> b;
        graph[a].emplace_back(b);
        graph[b].emplace_back(a);
    }

    fin.close();
}

void euler(int node) {
    while (!graph[node].empty()) {
        st.push(node);
        int son = graph[node].back();
        graph[node].pop_back();
        graph[son].erase(find(graph[son].begin(), graph[son].end(), node));
        node = son;
    }
}

void dfs(int node) {
    visited.set(node);

    for (const auto &son : graph[node]) {
        if (!visited[son]) {
            dfs(son);
        }
    }
}

void solve() {
    ofstream fout("ciclueuler.out");

    dfs(1);
    for (int i = 1; i <= n; ++i) {
        if (!visited[i] || (int) graph[i].size() & 1) {
            fout << "-1";
            return;
        }
    }

    int node = 1;
    do {
        euler(node);
        node = st.top();
        st.pop();
        fout << node << ' ';
    } while (!st.empty());

    fout.close();
}

int main() {
    read();
    solve();
    return 0;
}