Cod sursa(job #873015)

Utilizator cernat.catallinFMI Cernat Catalin Stefan cernat.catallin Data 6 februarie 2013 20:10:57
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <stdio.h>
#include <vector>
#include <stack>
#include <list>
#include <queue>
using namespace std;

#define Nmax 100001

vector < list<int> > graf;
list <int> ciclu;
list <int>::iterator it, last;
queue <int> coada;
stack <int> stiva;

int deg[Nmax], vizitat[Nmax];
int n, m;

void citire(){
    int x, y, j;
    char cc[100];
    scanf("%i %i", &n, &m);
    graf.resize(n+1);
    fgets(cc, 100, stdin);

    for(register int i = 1; i <= m; ++i){
        fgets(cc, 100, stdin);
        x = y = j = 0;
        while(cc[j] != ' ') x = x * 10 + cc[j] - '0', ++j;
        ++j;
        while(cc[j] != '\n') y = y * 10 + cc[j] - '0', ++j;

        ++deg[x]; ++deg[y];
        graf[x].push_back(y);
        graf[y].push_back(x);
    }
    fclose(stdin);
}

void bfs(int v){
    int first = v;
    coada.push(1);

    while(!coada.empty()){
        first = coada.front();
        coada.pop();
        it = graf[first].begin();
        last = graf[first].end();

        for(; it != last; ++it)
            if(!vizitat[*it]) coada.push(*it), vizitat[*it] = 1;
    }
}

int conex(){
    bfs(1);
    for(int i = 1; i <= n; ++i)
        if(!vizitat[i]) return 0;
    return 1;
}

int eulerian(){
    if( !conex() ) return 0;
    for(int i = 1; i <= n; ++i)
        if(deg[i] % 2 != 0) return 0;
    return 1;
}

inline void sterge(int v, int w){
    --deg[v]; --deg[w];
    graf[v].pop_front();

    it = graf[w].begin();
    last = graf[w].end();

    for(; it != last; ++it)
        if(*it == v){
            graf[w].erase(it);
            break;
        }
}

inline void euler(int v){
    int w;
    while( true ){
        if( graf[v].empty() ) break;
        w = graf[v].front();
        sterge(v, w);
        stiva.push(v);
        v = w;
    }
}

int rez(){
    int v = eulerian();
    if(v == 0) return 0;
    do{
        euler(v);
        v = stiva.top(); stiva.pop();
        ciclu.push_back(v);
    } while( !stiva.empty() );

    return 1;
}

void afis(int x){
    if(!x) printf("-1\n");
    else{
        it = ciclu.begin();
        last = ciclu.end();
        for(; it != last; ++it)
            printf("%i ", *it);
    }
    printf("\n");
    fclose(stdout);
}

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

    citire();
    afis( rez() );
}