Cod sursa(job #1577485)

Utilizator mariusn01Marius Nicoli mariusn01 Data 23 ianuarie 2016 14:56:01
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <vector>
#include <bitset>
#define DIM 100010
using namespace std;

vector < pair<int, int> > L[DIM];
bitset<DIM> b;
bitset<5*DIM> w;
int D[DIM];
int S[5*DIM];

int n, m, k, i, x, y, s, node, vecin,muchie;
ifstream fin ("ciclueuler.in");
ofstream fout("ciclueuler.out");

void dfs(int nod) {
    b[nod] = 1;
    for ( vector< pair<int, int> >::iterator it = L[nod].begin(); it!=L[nod].end(); it++ )
        if (b[ it->first ] == 0)
            dfs(it->first);
}

int main () {
    fin>>n>>m;
    for (i=1;i<=m;i++) {
        fin>>x>>y;
        L[x].push_back( make_pair(y, i) );
        L[y].push_back( make_pair(x, i) );
        D[x] ++;
        D[y] ++;
    }

    for (i=1;i<=n;i++)
        if (D[i] != 0) {
            s = i;
            dfs(i);
            break;
        }

    for (i=1;i<=n;i++) {
        if (D[i] % 2 == 1) {
            fout<<-1;
            return 0;
        }
        if (b[i] == 0 && D[i]!=0) {
            // am mai multe componente conexe cu muchii
            fout<<-1;
            return 0;
        }
    }

    int first = 1;
    k = 1;
    S[k] = s; // un nod ce are sigur gradul nenul
    while (k!=0) {
        // iau nodul din varful stivei
        node = S[k];
        if (D[node] == 0) {

            if (first == 1)
                first = 0;
            else
                fout<<S[k]<<" ";

            k--;
            continue;
        }
        while ( w[L[node][ L[node].size()-1 ].second] == 1 )
            L[node].pop_back();
        // D[node] fiind nenul sigur voi gasi si o muchie nestearsa
        vecin = L[node][ L[node].size()-1 ].first;
        muchie = L[node][ L[node].size()-1 ].second;

        k++;
        S[k] = vecin;

        // sterg muchia
        D[node]--;
        D[vecin]--;
        w[muchie] = 1;
    }
    return 0;
}