Cod sursa(job #1921145)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 martie 2017 11:32:39
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <algorithm>
#include <fstream>
#include <vector>

using namespace std;

using Graph = vector<vector<int>>;

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

void Dfs(Graph &g, int node, vector<int> &cycle)
{
    while (!g[node].empty()) {
        int next = g[node].back();
        g[node].pop_back();
        g[next].erase(find(g[next].begin(), g[next].end(), node));
        Dfs(g, next, cycle);
    }
    cycle.push_back(node);
}

vector<int> FindCycle(Graph &g)
{
    vector<int> cycle;
    Dfs(g, 0, cycle);
    cycle.pop_back();
    return cycle;
}

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

    auto cycle = FindCycle(graph);
    for (int node : cycle) {
        fout << node + 1 << " ";
    }

    return 0;
}