Cod sursa(job #1888711)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 22 februarie 2017 12:05:41
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>

using namespace std;

void DFS (unsigned int node);

ifstream fin ("ciclueuler.in");
ofstream fout ("ciclueuler.out");

unsigned int N, M;
unsigned int u[500001], v[500001];

vector <int> G[100001];
int pos[100001];
bool seen[100001];
int K;
int i, k;

int sol[100001];

int main ()
{
    fin >> N >> M;                          /// READ
    for (i=1; i<=M; i++)
    {
        fin >> u[i] >> v[i];
        G[u[i]].push_back(i);
        G[v[i]].push_back(i);
    }
    for (i=1; i<=N; i++)                    /// We are testing if we have an Euler cycle.
        if (G[i].size()%2 == 1)             /// It's an Euler cycle if all the nodes have even degrees.
        {
            fout << -1;                     /// If one node, at least, has odd degree, then it's not an Euler cycle.
            return 0;
        }
    DFS(1);                                 /// We start the algorithm with the first node.
    for (i=1; i<k; i++)                     /// PRINT
        fout << sol[i] << ' ';
    return 0;
}

void DFS (unsigned int node)                /// EULER
{
    while (pos[node] < G[node].size())      /// While node has neighbors...
    {
        K = G[node][pos[node]];             /// We are using a random node, K.
        pos[node]++;                        /// We delete it, so we'll not use it again.
        if (!seen[K])                       /// If K was not seen...
        {
            seen[K] = 1;                    /// We mark it as seen.
            DFS(u[K]+v[K]-node);            /// We continue the algorithm.
        }
    }
    sol[++k] = node;                        /// Add node as a solution.
}