-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsu_on_trees.cpp
More file actions
64 lines (51 loc) · 1.45 KB
/
dsu_on_trees.cpp
File metadata and controls
64 lines (51 loc) · 1.45 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
/*
-> DSU on trees
-> Can be used for answering queries related to the values in the subtree of all the nodes in a tree in O(NlogN).
-> ref:
1. https://codeforces.com/blog/entry/44351
2. https://codeforces.com/blog/entry/67696
*/
vector<int> adj[N]; // adjacency list
vector<int> vec[N]; // vec[i] -> nodes in the subtree of node 'i'
vector<int> subtree(N, 1), val(N);
vector<int> cnt(N);
int dfsSubtree(int x, int par) {
for (auto &c : adj[x]) {
if (c != par) {
dfsSubtree(c, x);
subtree[x] += subtree[c];
}
}
}
void dfs(int x, int par, bool keep) {
int mx = -1, big_child = -1;
for (auto &c : adj[x]) {
if (c != par && subtree[c] > mx) {
mx = subtree[c];
big_child = c;
}
}
for (auto &c : adj[x]) {
if (c != par && c != big_child)
dfs(c, x, false);
}
if (big_child != -1) {
dfs(big_child, x, true);
swap(vec[x], vec[big_child]);
}
vec[x].pb(x);
++cnt[val[x]];
for (auto &c : adj[x]) {
if (c == par || c == big_child)
continue;
for (auto &u : vec[c]) {
++cnt[val[u]];
vec[x].pb(u);
}
}
// at this moment, cnt[] has the value distribution for subtree of 'x'
if (!keep) {
for (auto c : vec[x])
--cnt[val[c]];
}
}