Cod sursa(job #2124350)

Utilizator ioanailincaMoldovan Ioana Ilinca ioanailinca Data 7 februarie 2018 09:42:28
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

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

int N, M;
vector <vector <int> > g;
vector <pair <int, int> > edges;
vector <bool> usedEdge;
vector <int> ciclu;
stack <int> stk;

void readGraph() {
    fin >> N >> M;
    g.resize(N + 1);
    edges.resize(M + 1);
    usedEdge.resize(M + 1, false);

    int x, y;
    for (int i = 1; i <= M; ++i) {
        fin >> x >> y;
        edges[i] = {x, y};
        g[x].push_back(i);
        g[y].push_back(i);
    }
}

bool checkEuler() {
    for (auto x: g) {
        if (x.size() % 2 == 1)
            return 0;
    }
    return 1;
}

void generateCycle(int node) {
    int p;
    for (const int& edge: g[node]) {
        if (!usedEdge[edge]) {
            p = edges[edge].first;
            usedEdge[edge] = 1;
            if (p == node)
                p = edges[edge].second;
            generateCycle(p);
        }
    }
    ciclu.push_back(node);
}

void generateIterativeCycle() {
    int currentNode;
    stk.push(1);

    int p;
    while (stk.size()) {
        currentNode = stk.top();
        if (g[currentNode].size()) {
            if (usedEdge[g[currentNode].back()])
                g[currentNode].pop_back();
            else {
                p = edges[g[currentNode].back()].first;
                if (currentNode == p)
                    p = edges[g[currentNode].back()].second;
                usedEdge[g[currentNode].back()] = 1;
                stk.push(p);
            }
        }
        else {
            ciclu.push_back(stk.top());
            stk.pop();
        }
    }
}

int main()
{
    readGraph();
    if (checkEuler()) {
        generateIterativeCycle();
        ciclu.pop_back();
        for (auto& t: ciclu)
            fout << t << ' ';
    }
    else
        fout << -1;

    fin.close();
    fout.close();
    return 0;
}