Pagini recente » Cod sursa (job #1526388) | Cod sursa (job #2099971) | Cod sursa (job #1629427) | Cod sursa (job #100134) | Cod sursa (job #2450036)
#include <iostream>
#include <fstream>
#include <set>
#include <stack>
#include <list>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
multiset<int> G[100005], Gaux[100005];
bool viz[100005], hasEven[100005];
int main()
{
int m, n, i, j, x, y, sel;
fin >> n >> m; sel = n;
for(i = 1; i <= m; i++){
fin >> x >> y;
G[x].insert(y); G[y].insert(x);
Gaux[x].insert(y); Gaux[y].insert(x);
hasEven[x] = 1 - hasEven[x];
hasEven[y] = 1 - hasEven[y];
}
/// Eulerian check
stack<int> st; st.push(1); viz[1] = 1;
while(!st.empty()){
x = st.top();
if(!Gaux[x].empty()){
do{ y = *(Gaux[x].begin());
Gaux[x].erase(Gaux[x].begin());
Gaux[y].erase(x);
}while(viz[y] && !Gaux[x].empty());
if(viz[y]) st.pop();
else st.push(y), viz[y] = 1;
}
else st.pop();
}
for(i = 1; i <= n; i++) if(viz[i] == 0 || hasEven[i] == 1) break;
if(i <= n){ fout << -1; return 0;} /// not Eulerian
list<int> cyc;
list<int>::iterator here;
st.push(1); cyc.push_back(1);
here = cyc.begin();
while(!st.empty()){
x = st.top();
if(!G[x].empty()){
y = *(G[x].begin()); G[x].erase(G[x].begin());
G[y].erase(G[y].find(x));
st.push(y);
here = cyc.insert(here, y);
}
else st.pop(), here++;
}
cyc.reverse(); cyc.pop_back();
for(here = cyc.begin(); here != cyc.end(); here++)
fout << *here << " ";
return 0;
}