Pagini recente » Cod sursa (job #1022640) | Cod sursa (job #31664) | Cod sursa (job #1403050) | Cod sursa (job #31656) | Cod sursa (job #1426090)
// Hierholzer's algorithm
#include <vector>
#include <list>
#include <array>
#include <algorithm>
#include <fstream>
#include <stack>
using namespace std;
const int nmax = 100005;
vector<int> graph[nmax];
array<int, nmax> visited;
vector<int> solution;
stack<int> st;
int n, m;
int found;
void read() {
ifstream in("ciclueuler.in");
int u, v;
in >> n >> m;
for (int i = 1; i <= m; ++i) {
in >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
}
void dfs(int u) {
visited[u] = 1;
++found;
for (auto v : graph[u])
if (!visited[v]) dfs(v);
}
void remove_edge(int u, int v) {
graph[u].pop_back();
for (auto it = graph[v].begin(); it != graph[v].end(); ++it)
if (*it == u) {
swap(*it, graph[v].back());
graph[v].pop_back();
return;
}
}
bool is_euler() {
for (int i = 1; i <= n; ++i)
if (graph[i].size() % 2 != 0)
return 0;
dfs(1);
if (found != n)
return 0;
return 1;
}
void euler_tour(int x) {
st.push(x);
while (!st.empty()) {
int u = st.top();
while (!graph[u].empty()) {
int v = graph[u].back();
remove_edge(u, v);
st.push(v);
u = v;
}
solution.push_back(u);
st.pop();
}
}
void write(bool is_good) {
ofstream out("ciclueuler.out");
if (!is_good) {
out << "-1\n";
}
else {
euler_tour(1);
solution.pop_back();
for (auto u : solution)
out << u << ' ';
}
}
int main() {
read();
write(is_euler());
return 0;
}