Cod sursa(job #2285070)

Utilizator preda.andreiPreda Andrei preda.andrei Data 18 noiembrie 2018 00:02:10
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <algorithm>
#include <fstream>
#include <list>
#include <stack>
#include <vector>

using namespace std;

struct Node
{
    list<int> edges;
    int degree = 0;
};

using Graph = vector<Node>;

void Dfs(const Graph &g, int node, vector<bool> &visited)
{
    visited[node] = true;
    for (const auto &next : g[node].edges) {
        if (!visited[next]) {
            Dfs(g, next, visited);
        }
    }
}

bool HasCycle(const Graph &g)
{
    for (const auto &node : g) {
        if (node.degree & 1) {
            return false;
        }
    }

    vector<bool> visited(g.size(), false);
    Dfs(g, 0, visited);

    for (const auto &elem : visited) {
        if (!elem) {
            return false;
        }
    }
    return true;
}

void RemoveEdge(Graph &g, int a, int b)
{
    g[a].edges.erase(find(g[a].edges.begin(), g[a].edges.end(), b));
    g[b].edges.erase(find(g[b].edges.begin(), g[b].edges.end(), a));
}

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

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

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

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

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

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

    return 0;
}