Cod sursa(job #1921232)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 martie 2017 11:48:08
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <algorithm>
#include <list>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

using Graph = vector<list<int>>;

bool IsEulerian(const vector<int> &deg)
{
    for (int i : deg) {
        if (i % 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);
    vector<int> degree(n, 0);

    while (m--) {
        int x, y;
        fin >> x >> y;
        graph[x - 1].push_front(y - 1);
        graph[y - 1].push_front(x - 1);
        ++degree[x - 1];
        ++degree[y - 1];
    }

    if (!IsEulerian(degree)) {
        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].front();
            st.push(next);
            graph[node].pop_front();
            graph[next].erase(find(graph[next].begin(), graph[next].end(), node));
        }
    }

    return 0;
}