Cod sursa(job #915247)

Utilizator razvan9310FMI - Razvan Damachi razvan9310 Data 14 martie 2013 21:01:19
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;

void DepthFirstSearch(int vertex, vector<int> *&Graph, bool *seen, vector<int> &cycle, int &finish)
{
    int i, j;
    seen[vertex] = 1;
    finish = vertex;
    for (i=0; i<Graph[vertex].size(); ++i)
    {
        int adjancted = Graph[vertex][i];
        if (!seen[adjancted])
        {
            DepthFirstSearch(adjancted, Graph, seen, cycle, finish);
            cycle.push_back(adjancted);
            cycle.push_back(vertex);

            for (j=0; Graph[adjancted][j]!=vertex; ++j);
            Graph[adjancted][j] = Graph[adjancted][Graph[adjancted].size()-1];
            Graph[adjancted].pop_back();

            Graph[vertex][i] = Graph[vertex][Graph[vertex].size()-1];
            Graph[vertex].pop_back();
            --i;
        }
    }
}

bool noEdges(vector<int> *Graph, int N)
{
    for (int i=1; i<=N; ++i)
        if (Graph[i].size())
            return 0;
    return 1;
}

int main()
{
    ifstream in("ciclueuler.in");
    ofstream out("ciclueuler.out");
    int N, M, i, a, b, finish;
    vector<int> *Graph, cycle;
    bool *seen;

    in>>N>>M;
    Graph = new vector<int>[N+1];
    seen = new bool[N+1];
    memset(seen, 0, sizeof(seen));
    for (i=0; i<M; ++i)
    {
        in>>a>>b;
        Graph[a].push_back(b);
        Graph[b].push_back(a);
    }

    DepthFirstSearch(1, Graph, seen, cycle, finish);

    /*if (Graph[finish].size() > 1)
    {
        out<<-1;
        return 0;
    }
    int other = Graph[finish][0];
    if (Graph[other].size() > 1)
    {
        out<<-1;
        return 0;
    }

    for (i=1; i<=N; ++i)
        if (i!=finish && i!=other && Graph[i].size())
        {
            out<<-1;
            return 0;
        }*/


    vector<int>::iterator it=cycle.begin(), stop=cycle.end();
    while (it != stop)
    {
        out<<*it<<" ";
        ++it;
    }

    /*for (i=1; i<=N; ++i)
    {
        for (int j=0; j<Graph[i].size(); ++j)
            out<<Graph[i][j]<<" ";
        out<<"\n";
    }*/
    return 0;
}