- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheuler_circ.cpp
More file actions
Latest commit
71 lines (69 loc) · 2.11 KB
/
Copy patheuler_circ.cpp
File metadata and controls
71 lines (69 loc) · 2.11 KB
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
#include"../0-common/common.hpp"
// what: build an Eulerian circuit in an undirected multigraph (adjacency matrix).
// time: O(n^2+m); memory: O(n^2)
// constraint: 1-indexed; all nonzero-degree nodes connected.
// usage: euler_cir g; g.init(n); g.add_edge(u,v); if (g.can()) auto path=g.run(1);
structeuler_cir {
int n;
vector<vector<int>> adj;
vector<int> nxt, path;
voidinit(int n_) {
// goal: allocate adjacency matrix and reset state.
n = n_;
adj.assign(n + 1, vector<int>(n + 1));
nxt.assign(n + 1, 1);
path.clear();
}
voidadd_edge(int u, int v, int c = 1) {
// goal: add c parallel edges between u and v.
if (u == v) adj[u][u] += 2 * c;
else adj[u][v] += c, adj[v][u] += c;
}
boolcan() {
// result: whether an Euler circuit exists.
vector<int> deg(n + 1);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) deg[i] += adj[i][j];
for (int i = 1; i <= n; i++)
if (deg[i] & 1) return0;
int s = 0;
for (int i = 1; i <= n; i++)
if (deg[i]) {
s = i;
break;
}
if (!s) return1;
vector<int> vis(n + 1);
queue<int> q;
q.push(s);
vis[s] = 1;
while (!q.empty()) {
int v = q.front();
q.pop();
for (int i = 1; i <= n; i++)
if (adj[v][i] && !vis[i]) vis[i] = 1, q.push(i);
}
for (int i = 1; i <= n; i++)
if (deg[i] && !vis[i]) return0;
return1;
}
voiddfs(int v) {
// goal: Hierholzer DFS to build circuit.
for (int &i = nxt[v]; i <= n; i++) {
while (i <= n && adj[v][i]) {
adj[v][i]--;
adj[i][v]--;
dfs(i);
}
}
path.push_back(v);
}
vector<int> run(int s = 1) {
// result: Euler circuit starting from s (if exists).
for (int i = 1; i <= n; i++) nxt[i] = 1;
path.clear();
dfs(s);
reverse(all(path));
return path;
}
};