Pagini recente » Cod sursa (job #2421158) | Cod sursa (job #2481291) | Cod sursa (job #2424937) | Cod sursa (job #1881106) | Cod sursa (job #2814955)
#include <iostream>
#include <fstream>
#include <vector>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
std::ifstream f("ciclueuler.in");
std::ofstream g("ciclueuler.out");
int n, m;
typedef unsigned long long ULL;
std::vector<std::vector<int> > la;
std::unordered_map<ULL, int> edges;
std::vector<int> cycle;
std::vector<int> deg;
void dfs(int x) {
struct stackInfo {
int currentNode;
int currentIndex;
};
std::stack<stackInfo> s;
s.push({ 1,0 });
while (!s.empty()) {
auto top = s.top();
s.pop();
int n = top.currentNode;
int i = top.currentIndex;
if (i == la[n].size()) {
cycle.push_back(n);
continue;
}
s.push({ n, i + 1 });
if (edges[(std::min(n, la[n][i]) << 18) | std::max(n, la[n][i])]) {
edges[(std::min(n, la[n][i]) << 18) | std::max(n, la[n][i])]--;
s.push({ la[n][i], 0 });
}
}
}
//void dfs(int x) {
// for (const int& i : la[x]) {
// if (edges[(std::min(x,i) << 18) | std::max(x,i)]) {
// edges[(std::min(x,i) << 18) | std::max(x,i)]--;
// dfs(i);
// }
// }
//
// cycle.push_back(x);
//}
bool checkEuler() {
for (int i = 1; i <= n; ++i)
if (deg[i] & 1) return false;
std::queue<int> q;
q.push(1);
std::vector<bool>used(n + 1);
used[1] = 1;
while (!q.empty()) {
int t = q.front();
q.pop();
for(int i : la[t])
if (!used[i]) {
used[i] = 1;
q.push(i);
}
}
for (int i = 1; i <= n; ++i)
if (!used[i])return false;
return true;
}
int main() {
f >> n >> m;
la.resize(n + 1);
deg.resize(n + 1);
for (int i = 0; i < m; ++i) {
int x, y;
f >> x >> y;
deg[x]++;
deg[y]++;
if (x > y)
std::swap(x, y);
edges[ (x << 18) | y]++;
if (edges[(x << 18) | y] == 1) {
la[x].push_back(y);
if(y != x)
la[y].push_back(x);
}
}
if (!checkEuler()) {
g << -1;
}
else {
dfs(1);
cycle.pop_back();
for (int i : cycle)
g << i << ' ';
}
}