Cod sursa(job #1896565)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 februarie 2017 19:18:50
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <algorithm>
#include <fstream>
#include <list>
#include <stack>
#include <vector>

using namespace std;

using Graph = vector<list<int>>;

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

inline void RemoveEdge(Graph &g, int x, int y)
{
    g[x].erase(find(g[x].begin(), g[x].end(), y));
    g[y].erase(find(g[y].begin(), g[y].end(), x));
}

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

    int n, m;
    fin >> n >> m;
    fin.get();

    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 (!Eulerian(graph)) {
        fout << "-1\n";
        return 0;
    }

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

    while (!st.empty()) {
        int node = st.top();

        while (!graph[node].empty()) {
            int next = graph[node].front();
            RemoveEdge(graph, node, next);

            st.push(next);
            node = next;
        }

        if (st.size() > 1) {
            fout << st.top() + 1 << " ";
        }
        st.pop();
    }

    return 0;
}