Cod sursa(job #2247709)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 septembrie 2018 23:04:45
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <algorithm>
#include <fstream>
#include <list>
#include <stack>
#include <vector>

using namespace std;

using Graph = vector<list<int>>;

void RemoveEdge(Graph &g, int node1, int node2)
{
    g[node1].erase(find(g[node1].begin(), g[node1].end(), node2));
    g[node2].erase(find(g[node2].begin(), g[node2].end(), node1));
}

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

    int nodes, edges;
    fin >> nodes >> edges;

    vector<list<int>> graph(nodes);
    vector<int> degrees(nodes, 0);

    for (int i = 0; i < edges; i += 1) {
        int a, b;
        fin >> a >> b;
        graph[a - 1].push_front(b - 1);
        graph[b - 1].push_front(a - 1);
        degrees[a - 1] += 1;
        degrees[b - 1] += 1;
    }

    for (const auto &deg : degrees) {
        if (deg % 2 == 1) {
            fout << "-1\n";
            return 0;
        }
    }

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

    while (!st.empty()) {
        auto node = st.top();
        if (graph[node].empty()) {
            st.pop();
            if (!st.empty()) {
                fout << node + 1 << " ";
            }
        } else {
            auto next = graph[node].front();
            st.push(next);
            RemoveEdge(graph, node, next);
        }
    }
    fout << "\n";

    return 0;
}