Cod sursa(job #1422928)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 20 aprilie 2015 12:25:59
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
using namespace std;

void euler(int node, vector<int> adjList[], vector<int> &cycle);
void deleteEdge(int node, int neighbor, vector<int> adjList[]);

int main()
{
    int N, M, u, v, i;
    ifstream f("ciclueuler.in");
    f >> N >> M;

    vector<int> adjList[N + 1];
    int grade[N + 1];
    fill(grade, grade + N + 1, 0);

    for (i = 1; i <= M; i++)
    {
        f >> u >> v;
        grade[u]++;
        grade[v]++;
        adjList[u].push_back(v);
        adjList[v].push_back(u);
    }
    f.close();

    ofstream g("ciclueuler.out");

    bool isEulerian = true;
    for (i = 1; i <= N && isEulerian; i++)
        if (grade[i] % 2 != 0)
            isEulerian = false;

    if (isEulerian)
    {
        vector<int> cycle;
        euler(u, adjList, cycle);
        for (i = 0; i < cycle.size(); i++)
            g << cycle[i] << " ";
    }
    else
        g << "-1";
    g.close();
    return 0;
}

void euler(int node, vector<int> adjList[], vector<int> &cycle)
{
    int neighbor;
    while (adjList[node].size())
    {
        neighbor = adjList[node][0];
        deleteEdge(node, neighbor, adjList);
        euler(neighbor, adjList, cycle);
    }
    cycle.push_back(node);
}

void deleteEdge(int node, int neighbor, vector<int> adjList[])
{
    bool found = false;
    for (auto it = adjList[node].begin(); it != adjList[node].end() && !found; it++)
        if (*it == neighbor)
            adjList[node].erase(it), found = true;
    found = false;
    for (auto it = adjList[neighbor].begin(); it != adjList[neighbor].end() && !found; it++)
        if (*it == node)
            adjList[neighbor].erase(it), found = true;
}