Pagini recente » Cod sursa (job #1780368) | Monitorul de evaluare | Rating Maria Mosneag (maria.mosneag) | Cod sursa (job #954603) | Cod sursa (job #2814858)
#include <iostream>
#include <fstream>
#include <vector>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <queue>
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) {
for (int i : la[x]) {
int p1 = std::min(x, i);
int p2 = std::max(x, i);
if (edges[{p1, p2}] > 0) {
edges[{p1, p2}]--;
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]++;
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 << ' ';
}
}