Pagini recente » Cod sursa (job #2848096) | Cod sursa (job #1216220) | Istoria paginii runda/ppp/clasament | Cod sursa (job #1966456) | Cod sursa (job #1896388)
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
using Graph = vector<vector<int>>;
inline bool Eulerian(const Graph &g)
{
for (const auto &node : g) {
if (node.size() % 2 != 0) {
return false;
}
}
return true;
}
inline void RemoveEdge(Graph &g, int x, int y)
{
g[x].erase(find(g[x].begin(), g[x].end(), y));
g[y].erase(find(g[y].begin(), g[y].end(), x));
}
void Dfs(Graph &g, int node, vector<int> &cycle)
{
while (!g[node].empty()) {
int neighbour = g[node].back();
RemoveEdge(g, node, neighbour);
Dfs(g, neighbour, cycle);
}
cycle.push_back(node);
}
vector<int> FindEulerianCycle(Graph &g)
{
vector<int> cycle;
Dfs(g, 0, cycle);
cycle.pop_back();
return cycle;
}
int main()
{
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
int n, m;
fin >> n >> m;
Graph graph(n);
while (m--) {
int x, y;
fin >> x >> y;
graph[x - 1].push_back(y - 1);
graph[y - 1].push_back(x - 1);
}
if (!Eulerian(graph)) {
fout << "-1\n";
return 0;
}
auto cycle = FindEulerianCycle(graph);
for (int node : cycle) {
fout << node + 1 << " ";
}
fout << "\n";
return 0;
}