-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler_tour.h
92 lines (84 loc) · 2.41 KB
/
euler_tour.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* Hierholzer's algorithm */
#include <vector>
#include <algorithm>
template<typename AdjMatrix>
void euler_tour_adj_matrix_directed(AdjMatrix& adj, int u,
std::vector<int>& tour)
{
for (int v = 0; v < static_cast<int>(adj[u].size()); ++v) {
if (!adj[u][v]) continue;
adj[u][v] = 0;
euler_tour_adj_matrix_directed(adj, v, tour);
}
tour.push_back(u);
}
template<typename AdjMatrix>
std::vector<int> euler_tour_adj_matrix_directed(AdjMatrix& adj)
{
std::vector<int> ret;
euler_tour_adj_matrix_directed(adj, 0, ret);
std::reverse(ret.begin(), ret.end());
return ret;
}
template<typename AdjMatrix>
void euler_tour_adj_matrix_undirected(AdjMatrix& adj, int u,
std::vector<int>& tour)
{
for (int v = 0; v < static_cast<int>(adj[u].size()); ++v) {
if (!adj[u][v]) continue;
adj[u][v] = 0;
adj[v][u] = 0;
euler_tour_adj_matrix_undirected(adj, v, tour);
}
tour.push_back(u);
}
template<typename AdjMatrix>
std::vector<int> euler_tour_adj_matrix_undirected(AdjMatrix& adj)
{
std::vector<int> ret;
euler_tour_adj_matrix_undirected(adj, 0, ret);
std::reverse(ret.begin(), ret.end());
return ret;
}
template<typename AdjList>
void euler_tour_adj_list_directed(AdjList& adj, int u, std::vector<int>& tour)
{
while (!adj[u].empty()) {
int v = adj[u].back();
adj[u].pop_back();
euler_tour_adj_list_directed(adj, v, tour);
}
tour.push_back(u);
}
template<typename AdjList>
std::vector<int> euler_tour_adj_list_directed(AdjList& adj)
{
std::vector<int> ret;
euler_tour_adj_list_directed(adj, 0, ret);
std::reverse(ret.begin(), ret.end());
return ret;
}
template<typename AdjList>
void euler_tour_adj_list_undirected(AdjList& adj, int u, std::vector<int>& tour)
{
while (!adj[u].empty()) {
int v = adj[u].back();
adj[u].pop_back();
for (auto it = adj[v].begin(); it != adj[v].end(); ++it) {
if (*it == u) {
adj[v].erase(it);
break;
}
}
euler_tour_adj_list_undirected(adj, v, tour);
}
tour.push_back(u);
}
template<typename AdjList>
std::vector<int> euler_tour_adj_list_undirected(AdjList& adj)
{
std::vector<int> ret;
euler_tour_adj_list_undirected(adj, 0, ret);
std::reverse(ret.begin(), ret.end());
return ret;
}