Cod sursa(job #1937168)

Utilizator cristina_borzaCristina Borza cristina_borza Data 23 martie 2017 19:22:08
Problema Ciclu Eulerian Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <vector>
#include <stack>
#include <map>

#define DIM 600005

using namespace std;

ofstream g ("ciclueuler.out");

int grad[DIM], c[DIM], mp[DIM];
int n, nrs, x, y, m, nr;

vector <pair <int, int> > G[DIM];
stack <int> stiva;

void dfs (int node) {
    if (c[node] == 1)
        return;

    c[node] = 1;
    for (vector <pair <int, int> > :: iterator it = G[node].begin(); it != G[node].end(); ++it) {
        int qw = it -> first;
        if (c[qw] == 0) {
            c[qw] = 1;
            dfs (qw);
        }
    }

    int qw;
    qw = 1;
}

void euler () {
    stiva.push (1);
    int ok = 1;

    while (!stiva.empty ()) {
        int node = stiva.top();
        if (grad[node] == 0) {
            if (ok == 0) {
                g << node << " ";
            }

            ok = 0;
            stiva.pop();
        }

        else {
            while (!G[node].empty() && mp[G[node][G[node].size () - 1].second] == 1) {
                G[node].pop_back ();
            }

            if (G[node].empty ())
                continue;

            int v = G[node][G[node].size () - 1].first;
            int aux = G[node][G[node].size () - 1].second;
            mp[aux] = 1;

            --grad[node];
            --grad[v];

            stiva.push(v);
        }
    }
}


void read (int &x) {
    char ch;
    x = 0;

    while (!isdigit(ch = getchar())) {

    }

    do {
        x = x * 10 + ch - '0';
    }while (isdigit(ch = getchar()));
}

int main() {
    freopen ("ciclueuler.in", "r", stdin);

    read (n), read(m);
    for (int i = 1; i <= m; ++i) {
        read(x), read(y);
        G[x].push_back ({y, ++nr});
        G[y].push_back ({x, nr});

        ++grad[x];
        ++grad[y];
    }

    for (int i = 1; i <= n; ++i) {
        if (grad[i] % 2 == 1) {
            g << -1;
            return 0;
        }
    }

    dfs (1);
    for (int i = 1; i <= n; ++i) {
        if (c[i] == 0) {
            g << -1;
            return 0;
        }
    }

    euler ();
    return 0;
}