Cod sursa(job #2605138)

Utilizator lamuritorulIoan Pop lamuritorul Data 24 aprilie 2020 14:58:27
Problema Ciclu Eulerian Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <list>
#include <vector>
#include <stack>

using namespace std;

vector <list<int>> readGraph(const string& inputPath)
{
    int n, m;
    ifstream fin(inputPath);
    fin >> n >> m;
    vector<list<int>> graph(n);
    int x, y;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y;
        x--; y--;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    return graph;
}

void dfs(vector<list<int>> & graph, int source, vector<bool> & visited)
{
    visited[source] = true;
    for (auto y: graph[source])
        if (!visited[y])
            dfs(graph, y, visited);
}

bool isEulerian(vector<list<int>> & graph)
{
    for (const auto& edges: graph)
        if (edges.size() % 2 != 0)
            return false;
    vector<bool> visited(graph.size(), false);
    dfs(graph, 0, visited);
    for (bool v: visited)
        if (!v)
            return false;
    return true;
}

vector<int> eulerianCycle(vector<list<int>> & graph)
{
    vector<int> cycle;
    if (!isEulerian(graph))
    {
        cycle.push_back(-1);
        cycle.push_back(-1);
    }
    else
    {
        stack<int> nodes;
        nodes.push(0);
        int x, y;
        while (!nodes.empty())
        {
            x = nodes.top();
            if (graph[x].size() <= 0)
            {
                cycle.push_back(x);
                nodes.pop();
            }
            else
            {
                y = graph[x].front();
                graph[x].pop_front();
                graph[y].remove(x);
                nodes.push(y);
            }
        }
    }
    return cycle;
}

void writeCycle(const string& outPath, const vector<int>& cycle)
{
    ofstream fout(outPath);
    for (int i = 0;i < cycle.size() - 1; i++)
        fout << cycle[i] + 1 << " ";
    fout.close();
}

int main()
{
    auto graph = readGraph("ciclueuler.in");
    writeCycle("ciclueuler.out", eulerianCycle(graph));
    return 0;
}