Pagini recente » Cod sursa (job #3289034) | Clasament Tiberiu Popoviciu 2011, clasa a 9-a | Cod sursa (job #2122550) | Cod sursa (job #842824) | Cod sursa (job #2907570)
#include <bits/stdc++.h>
using namespace std;
ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");
const int NMAX = 1e5 + 10;
int n,m;
int viz[5 * NMAX], was[NMAX];
vector < pair < int, int > > v[NMAX];
void dfs(int node){
viz[node] = 1;
for(auto it: v[node])
if(!viz[it.first])
dfs(it.first);
}
int main(){
int i,x,y, nxt;
f >> n >> m;
for(i = 0 ; i < m ; i++){
f >> x >> y;
v[x].push_back({y, i});
v[y].push_back({x, i});
was[x]++;
was[y]++;
}
int root;
for(i = 1 ; i <= n ; i++)
if(was[i]){
dfs(i);
root = i;
break;
}
for(i = 1 ; i <= n ; i++){
if( (!viz[i] && was[i]) || v[i].size() % 2 == 1){
g << -1;
return 0;
}
viz[i] = 0;
}
int elem = 1, node, neighbour;
deque < int > q;
q.push_back(root);
bool ok = 0;
while (!q.empty()) {
node = q.back();
if (!was[node]) {
if (ok) {
g << node << " ";
q.pop_back();
continue;
}
else {
ok = 1;
q.pop_back();
continue;
}
}
while (!v[node].empty() && viz[v[node].back().second] == 1)
v[node].pop_back();
neighbour = v[node].back().first;
was[node]--;
was[neighbour]--;
viz[v[node].back().second] = 1;
v[node].pop_back();
q.push_back(neighbour);
}
return 0;
}