Cod sursa(job #1896458)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 februarie 2017 18:23:59
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <algorithm>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

using Graph = vector<vector<int>>;

inline 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;

    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);

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

    return 0;
}