Cod sursa(job #1582747)

Utilizator LolkekzorChiorean Tudor Lolkekzor Data 28 ianuarie 2016 13:40:12
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <list>
#include <stack>
#include <queue>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

int n, m, x, y, i, crt, nxt;
int grad[100100];
bool viz[100100];
list<int> graph[100100], solution;
stack<int> S;

int isEulerian() {
    queue<int> Q;
    int crt, i;

    Q.push(1);
    viz[1] = true;
    while(!Q.empty()) {
        crt = Q.front();
        Q.pop();
        for (list<int>::iterator it = graph[crt].begin() ; it != graph[crt].end() ; it++) {
            if (viz[*it] == false) {
                viz[*it] = true;
                Q.push(*it);
            }
        }
    }

    for (i = 1 ; i <= n ; i++) {
        if (viz[i] == false)
            return 0;
        if (grad[i] % 2 == 1 || grad[i] == 0)
            return 0;
    }

    return 1;
}

void kick(int crt, int nxt) {
    list<int>::iterator it;
    for (it = graph[nxt].begin() ; *it != crt ; it++);
    graph[nxt].erase(it);
}

int main()
{
    fin>>n>>m;
    for (i = 1 ; i <= m ; i++) {
        fin>>x>>y;
        graph[x].push_back(y);
        graph[y].push_back(x);
        grad[x]++; grad[y]++;
    }

    if (isEulerian() == 1) {
        S.push(1);
        while(!S.empty()) {
            crt = S.top();
            if(!graph[crt].empty()) {
                nxt = *graph[crt].begin();
                S.push(nxt);
                //graph[nxt].erase(graph[nxt].begin());
                kick(crt, nxt);
                graph[crt].erase(graph[crt].begin());
            } else {
                solution.push_back(S.top());
                S.pop();
            }
        }

        for (list<int>::iterator it = solution.begin() ; it != --solution.end() ; it++) {
            fout<<*it<<' ';
        }
    } else {
        fout<<-1;
    }

    return 0;
}