Pagini recente » Cod sursa (job #542414) | Cod sursa (job #1603624) | Cod sursa (job #1654704) | Cod sursa (job #1940379) | Cod sursa (job #3357887)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
int main() {
std::ifstream input("ciclueuler.in");
std::ofstream output("ciclueuler.out");
int n, m;
input >> n >> m;
std::vector<std::vector<int>> graph(n + 1);
std::vector<std::vector<bool>> removed(n + 1);
for (int i = 1; i <= n; ++i) {
removed[i].resize(graph[i].size(), false);
}
for (int i = 0; i < m; ++i) {
int x, y;
input >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
for (int i = 1; i <= n; ++i) {
removed[i].resize(graph[i].size(), false);
}
bool has_cycle = true;
for (int i = 1; i <= n; ++i) {
if (graph[i].size() % 2 == 1) {
has_cycle = false;
break;
}
}
if (!has_cycle) {
output << -1;
return 0;
}
std::vector<int> cycle;
std::stack<int> st;
st.push(1);
while (!st.empty()) {
int v = st.top();
bool found = false;
for (int i = 0; i < (int)graph[v].size(); ++i) {
if (!removed[v][i]) {
int u = graph[v][i];
removed[v][i] = true;
for (int j = 0; j < (int)graph[u].size(); ++j) {
if (graph[u][j] == v && !removed[u][j]) {
removed[u][j] = true;
break;
}
}
st.push(u);
found = true;
break;
}
}
if (!found) {
st.pop();
cycle.push_back(v);
}
}
cycle.pop_back();
for (int i = 0; i < (int)cycle.size(); ++i) {
output << cycle[i] << " ";
}
return 0;
}