Cod sursa(job #930750)

Utilizator ericptsStavarache Petru Eric ericpts Data 27 martie 2013 20:00:53
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <vector>
#include <stack>

#define pb push_back
#define forEach(G) for( typeof(G.begin()) it = G.begin() ; it != G.end() ; ++ it)

using namespace std;

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

const int maxn = 100100;

vector<int> SHOW;
vector<int> G[maxn];
stack<int> S;
int deg[maxn],n,m;
bool viz[maxn];

void read(){
    int i,a,b;
    in >> n >> m;
    for(i = 1 ; i <= m ; ++ i){
        in >> a >> b;
        deg[a]++;
        deg[b]++;
        G[a].pb(b);
        G[b].pb(a);
    }
}

void DFS(int nod){
    while(!S.empty())S.pop();
    S.push(nod);
    viz[nod] = 1;
    while(!S.empty()){
        nod = S.top();S.pop();
        forEach(G[nod]){
            if(viz[*it])continue;
            viz[*it] = 1;
            S.push(*it);
        }
    }
}

bool admisibil(){
    for(register int i = 1 ; i <= n ; ++ i)
        if(deg[i]&1)return 0;
    return 1;
}

bool bun(){
    DFS(1);
    bool good = 1;
    for(register int i = 1 ; i <= n & good ; ++ i)
        if(!viz[i])good = 0;
    return good && admisibil();
}

void euler(int nod){
    int aux;
    while(!G[nod].empty()){
        aux = G[nod].back();
        S.push(nod);
        deg[nod]--,deg[aux]--;
        G[nod].pop_back();
        forEach(G[aux])
            if(*it == nod){
                G[aux].erase(it);
                break;
            }
        nod = aux;
    }
}

void solve(){
    int nod = 1;
    if(!bun())return;
    while(!S.empty())S.pop();

    do{
        euler(nod);
        nod = S.top();S.pop();
        SHOW.pb(nod);
    }while(!S.empty());
}

void write(){
    if(SHOW.empty()){
        out << "-1\n";
    }else{
        forEach(SHOW){
            out << *it << " ";
        }out << "\n";
    }
}


int main(){
    read();
    solve();
    write();
    return 0;
}