Pagini recente » Cod sursa (job #2705366) | Cod sursa (job #2051309) | Cod sursa (job #1879368) | Cod sursa (job #2853933) | Cod sursa (job #3271696)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
std::ifstream f("ciclueuler.in");
std::ofstream g("ciclueuler.out");
const int NMAX = 1e5;
std::vector<int> L[NMAX + 1];
std::stack<int> st;
std::vector<int> cycle;
int viz[NMAX + 1];
int N, M;
bool isConnected() {
std::stack<int> dfsStack;
int visitedCount = 0;
dfsStack.push(1);
viz[1] = 1;
while (!dfsStack.empty()) {
int current = dfsStack.top();
dfsStack.pop();
visitedCount++;
for (int neighbor : L[current]) {
if (!viz[neighbor]) {
viz[neighbor] = 1;
dfsStack.push(neighbor);
}
}
}
return visitedCount == N;
}
void findEulerianCycle(int start) {
st.push(start);
while (!st.empty()) {
int current = st.top();
if (!L[current].empty()) {
int next = L[current].back();
L[current].pop_back();
for (auto it = L[next].begin(); it != L[next].end(); ++it) {
if (*it == current) {
L[next].erase(it);
break;
}
}
st.push(next);
}
else {
cycle.push_back(current);
st.pop();
}
}
}
int main() {
f >> N >> M;
for (int i = 1; i <= M; ++i) {
int x, y;
f >> x >> y;
L[x].push_back(y);
L[y].push_back(x);
}
for (int i = 1; i <= N; ++i) {
if (L[i].size() % 2 != 0) {
g << -1;
return 0;
}
}
if (!isConnected()) {
g << -1;
return 0;
}
findEulerianCycle(1);
for (auto it = cycle.rbegin(); it != cycle.rend(); ++it) {
g << *it << " ";
}
return 0;
}