-
Notifications
You must be signed in to change notification settings - Fork 10
/
centroid_decomposition.sublime-snippet
executable file
·88 lines (78 loc) · 1.92 KB
/
centroid_decomposition.sublime-snippet
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
<snippet>
<content><![CDATA[
const int LOGN = 18;
vector<int> g[N];
int dep[N], dp[LOGN][N];
bool mark[N];
int sz[N], par[N];
// Traversal is started from node 1.
// dp[i][x]: moving towards parent node = x + 2^i node in main tree
// dep[x]: depth of node x in main tree, descending from parent
void dfs2(int u, int p) {
for (auto v : g[u]) {
if (v == p) continue;
dep[v] = dep[u] + 1;
dp[0][v] = u;
dfs2(v, u);
}
}
void preprocess(int n) {
dep[1] = 0;
dp[0][1] = 1;
dfs2(1, 0);
for (int k = 1; k < LOGN; k++) {
for (int i = 1; i <= n; i++) {
dp[k][i] = dp[k-1][dp[k-1][i]];
}
}
}
int lca(int u, int v) {
if (dep[u] > dep[v]) swap(u, v);
int d = dep[v] - dep[u];
for (int k = LOGN - 1; k >= 0; k--) {
if (d & (1 << k))
v = dp[k][v];
}
if (u == v) return u;
for (int k = LOGN - 1; k >= 0; k--) {
if (dp[k][u] != dp[k][v])
u = dp[k][u], v = dp[k][v];
}
return dp[0][u];
}
int dis(int a, int b) {
return dep[a] + dep[b] - 2 * dep[lca(a, b)];
}
// --> Centroid Decomposition
int dfs(int u, int p) {
sz[u] = 1;
for (auto v : g[u]) {
if (v == p || mark[v]) continue;
sz[u] += dfs(v, u);
}
return sz[u];
}
int centroid(int u, int p, int n) {
for (auto v : g[u]) {
if (v == p || mark[v]) continue;
if (sz[v] > n / 2) return centroid(v, u, n);
}
return u;
}
void decompose(int u, int p) {
int n = dfs(u, p);
int c = centroid(u, p, n);
mark[c] = 1;
if (p == 0) p = c;
par[c] = p;
for (auto v : g[c]) {
if (!mark[v])
decompose(v, c);
}
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>centroidDecomposition</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>