Pagini recente » Cod sursa (job #764026) | Cod sursa (job #2768801) | Cod sursa (job #2137762) | Cod sursa (job #2511511) | Cod sursa (job #1361717)
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
int N, M;
vector <vector <int> > graph;
vector <int> degree, ans;
stack <int> last_node;
bool ConnectedAndEvenDegree() {
queue <int> que;
vector <bool> visited(N + 1);
if (degree[1] % 2 == 1) {
return false;
}
int left_nodes = N - 1;
que.push(1);
visited[1] = true;
while (!que.empty()) {
int iam = que.front();
que.pop();
for (auto to: graph[iam]) {
if (!visited[to]) {
visited[to] = true;
--left_nodes;
que.push(to);
if (degree[to] % 2 == 1) {
return false;
}
}
}
}
return (left_nodes == 0);
}
void DFS(int iam) {
while (true) {
if (graph[iam].empty()) {
break;
}
int to = graph[iam][0];
last_node.push(iam);
graph[iam].erase(graph[iam].begin());
for (auto w = graph[to].begin(); w != graph[to].end(); ++w) {
if (*w == iam) {
graph[to].erase(w);
break;
}
}
iam = to;
}
}
void FindCicles() {
int iam = 1;
do {
DFS(iam);
iam = last_node.top();
last_node.pop();
ans.push_back(iam);
} while (!last_node.empty());
}
int main() {
#ifdef INFOARENA
freopen("ciclueuler.in", "r", stdin);
freopen("ciclueuler.out", "w", stdout);
#else
freopen("/Users/duxar/Workplace/Xcode Projects/Selectie/Selectie/input", "r", stdin);
#endif
int i, x, y;
scanf("%d %d", &N, &M);
graph.resize(N + 1);
degree.resize(N + 1);
for (i = 1; i <= M; ++i) {
scanf("%d %d", &x, &y);
graph[x].push_back(y);
graph[y].push_back(x);
++degree[x];
++degree[y];
}
if (!ConnectedAndEvenDegree()) {
printf("-1\n");
return 0;
}
FindCicles();
for (auto iam: ans) {
printf("%d ", iam);
}
printf("\n");
return 0;
}