Cod sursa(job #1231620)

Utilizator PTAdrian64Pop-Tifrea Adrian PTAdrian64 Data 21 septembrie 2014 08:42:44
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <cstdio>
#define n_max 1000010

#define m_max 5000012

#include <list>

#include <queue>


#include <stack>

using namespace std;



int n,m,d[n_max];
bool s[n_max];
list <int> gr[n_max],h;
stack <int > st;
queue <int> qu;

void read_gr(){
int x,y;
freopen("ciclueuler.in","r",stdin);
scanf("%d %d", &n, &m);
while(m--){
scanf("%d %d",&x , &y);
d[x]++;d[y]++;
gr[x].push_back(y);
gr[y].push_back(x);
}
}

bool valid(){
int i;
qu.push(1);s[1]=1;
i=1;
while(!qu.empty()){
i=qu.front();
qu.pop();
for(list <int> :: iterator it = gr[i].begin() ;it != gr[i].end() ;it ++)
if(!s[*it]){
qu.push(*it);
s[*it]=1;
}
}
for(i = 1; i <= n; i ++)
if( (!s[i]) || (d[i] % 2))
return 0;
return 1;
}

void solve(){
if(valid()){
list <int> :: iterator it;
int x, y;
x=1;
do{
while(1){
if(gr[x].empty())break;
y=gr[x].front();
st.push(x);
d[x]--;d[y]--;
gr[x].pop_front();
for(it = gr[y].begin(); it != gr[y].end(); ++it)
if(*it == x){
gr[y].erase(it);
break;
}
x=y;
}
x=st.top();
st.pop();
h.push_back( x );
}while(!st.empty());
for(it= h.begin(); it != h.end(); ++ it)
printf("%d ", *it);
}
else
printf("-1");
}

int main(void){

freopen("ciclueuler.out","w",stdout);

read_gr();

solve();


}