模板——补充

树上启发式合并。

树上启发式合并

例如计算 \(\sum_{d(x)=d(y),1\le x<y\le n}d(y)-d(lca(x,y))\)

\(O(n\log n)\) 版:

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
vector<ll> e[N];
ll a[N], d[N], cnt[N], big[N], siz[N], ans;
ll dfn[N], L[N], R[N], index;
ll n, m;

ll dfs(ll root, ll dad) {
ll curb = 0;
d[root] = d[dad] + 1;
siz[root]++;
dfn[++index] = root;
L[root] = index;
for (auto son: e[root]) {
if (son == dad)
continue;
siz[root] += dfs(son, root);
if (siz[son] > curb) {
curb = siz[son];
big[root] = son;
}
}
R[root] = index;
return siz[root];
}

void dsu(ll root, ll dad, ll keep) {
for (auto son: e[root]) {
if (son == dad || son == big[root])
continue;
dsu(son, root, 0);
}
if (big[root])
dsu(big[root], root, 1);
for (auto son: e[root]) {
if (son == dad || son == big[root])
continue;
for (ll i = L[son]; i <= R[son]; i++) {
ans += cnt[d[dfn[i]]] * (d[dfn[i]] - d[root]);
}
for (ll i = L[son]; i <= R[son]; i++) {
cnt[d[dfn[i]]]++;
}
}
cnt[d[root]]++;
if (keep == 0) {
for (ll i = L[root]; i <= R[root]; i++) {
cnt[d[dfn[i]]]--;
}
}
}