Cod sursa(job #1428986)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 5 mai 2015 14:26:45
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

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

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)
        isEulerian = BFS(u, adjList, N);

    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;
    stack<int> st;
    st.push(node);
    while (!st.empty())
    {
        node = st.top();
        if (adjList[node].size())
        {
            st.push(adjList[node][0]);
            deleteEdge(node, adjList[node][0], adjList);
        }
        else
        {
            if (st.size() != 1)
                cycle.push_back(st.top());
            st.pop();
        }
        //euler(neighbor, adjList, cycle);
    }
}

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

bool BFS(int src, vector<int> adjList[], int N)
{
    bool visited[N + 1];
    fill(visited, visited + N + 1, false);
    visited[src] = true;

    queue<int> q;
    q.push(src);
    N--;
    int x;
    while(!q.empty())
    {
        x = q.front(), q.pop();
        for (auto it = adjList[x].begin(); it != adjList[x].end(); it++)
            if (!visited[*it])
            {
                N--;
                q.push(*it);
                visited[*it] = true;
            }
    }

    return !N;
}