Cod sursa(job #1921167)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 martie 2017 11:37:07
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <algorithm>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

using Graph = vector<vector<int>>;

bool IsEulerian(const Graph &g)
{
    for (const auto &node : g) {
        if (node.size() % 2 != 0) {
            return false;
        }
    }
    return true;
}

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

    int n, m;
    fin >> n >> m;

    Graph graph(n);
    while (m--) {
        int x, y;
        fin >> x >> y;
        graph[x - 1].push_back(y - 1);
        graph[y - 1].push_back(x - 1);
    }

    if (!IsEulerian(graph)) {
        fout << "-1\n";
        return 0;
    }

    stack<int> st;
    st.push(0);

    bool first_node = true;
    while (!st.empty()) {
        int node = st.top();
        if (graph[node].empty()) {
            st.pop();
            if (!first_node) {
                fout << node + 1 << " ";
            }
            first_node = false;
        } else {
            int next = graph[node].back();
            st.push(next);
            graph[node].pop_back();
            graph[next].erase(find(graph[next].begin(), graph[next].end(), node));
        }
    }

    return 0;
}