Pagini recente » Statistici Andreea (980346) | Cod sursa (job #2362090) | Cod sursa (job #2760772) | Istoria paginii runda/ceva_ez | Cod sursa (job #2814931)
#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;
struct pair_hash {
std::size_t operator () (const std::pair<int, int>& p) const {
auto h1 = std::hash<int>{}(p.first);
auto h2 = std::hash<int>{}(p.second);
return h1 ^ h2;
}
};
typedef std::pair<int, int> iPair;
std::vector<std::vector<int> > la;
std::unordered_map<iPair, int, pair_hash> 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 });
int vecin = la[n][i];
int p1 = std::min(n, vecin);
int p2 = std::max(n, vecin);
if (edges[{p1, p2}]) {
edges[{p1, p2}]--;
s.push({ vecin, 0 });
}
}
}
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, y}]++;
if (edges[{x, 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 << ' ';
}
}