-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheavy light decomposition.cpp
138 lines (65 loc) · 1.21 KB
/
heavy light decomposition.cpp
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<bits/stdc++.h>
using namespace std;
/////////////// Heavy Light Decomposition //////////////
#define MAXN 1005
vector<int> g[MAXN], c[MAXN];
int s[MAXN]; // subtree size
int p[MAXN]; // parent id
int r[MAXN]; // chain root id
int t[MAXN]; // index used in segtree/bit/...
int d[MAXN]; // depht
int ts;
void dfs(int v, int f) {
p[v] = f;
s[v] = 1;
if (f != -1) d[v] = d[f] + 1;
else d[v] = 0;
for (int i = 0; i < g[v].size(); ++i) {
int w = g[v][i];
if (w != f) {
dfs(w, v);
s[v] += s[w];
}
}
}
void hld(int v, int f, int k) {
t[v] = ts++;
c[k].push_back(v);
r[v] = k;
int x = 0, y = -1;
for (int i = 0; i < g[v].size(); ++i) {
int w = g[v][i];
if (w != f) {
if (s[w] > x) {
x = s[w];
y = w;
}
}
}
if (y != -1) {
hld(y, v, k);
}
for (int i = 0; i < g[v].size(); ++i) {
int w = g[v][i];
if (w != f && w != y) {
hld(w, v, w);
}
}
}
void init(int n) {
for (int i = 0; i < n; ++i) {
g[i].clear();
}
}
void add(int a, int b) {
g[a].push_back(b);
g[b].push_back(a);
}
void build() {
ts = 0;
dfs(0, -1);
hld(0, 0, 0);
}
/////////////// Heavy Light Decomposition //////////////
int main() {
}