Cod sursa(job #1993716)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 23 iunie 2017 17:05:41
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <stack>

struct Edge {
    int from, to;
    bool check;
};

void visit(int &sum, std::vector<std::list<int>> &graph,
    std::vector<Edge> &edges, std::vector<int> &res) {

    std::stack<int> myStack;
    myStack.push(1);

    bool fin;

    while (!myStack.empty()) {
        fin = true;
        for (int edge : graph[myStack.top()]) {
            if (edges[edge].check) {

                fin = false;

                edges[edge].check = false;
                sum++;

                if (edges[edge].from != myStack.top()) {
                    myStack.push(edges[edge].from);
                } else {
                    myStack.push(edges[edge].to);
                }

                break;
            }
        }
        if (fin) {
            res.push_back(myStack.top());
            myStack.pop();
        }
    }
}

int main() {
    std::ifstream fileIn("ciclueuler.in");
    std::ofstream fileOut("ciclueuler.out");

    int nV, nM;

    fileIn >> nV >> nM;

    std::vector<std::list<int>> graph(nV + 1);
    std::vector<Edge> edges(nM);

    int a, b;
    for (int i(0); i < nM; i++) {
        fileIn >> a >> b;

        edges[i].from = a;
        edges[i].to = b;
        edges[i].check = true;

        graph[a].push_back(i);
        graph[b].push_back(i);
    }

    std::vector<int> res;

    int sum(0);
    visit(sum, graph, edges, res);

    if (sum != nM) {
        fileOut << -1;
    } else {
        for (int node : res) {
            fileOut << node << ' ';
        }
    }

    fileIn.close();
    fileOut.close();
    return 0;
}