简介

重心

树的重心是这样一个节点:以它为根时,任何其他节点的子树大小都不超过 N2\frac N2。

重点例题 – 继续学习之前,请先尽力独立解决这道题!

View Internal Solution

可以从根开始寻找重心。每一步遍历当前节点的所有子节点;若它们的子树大小均不超过 N2\frac N2,当前节点就是重心。否则,移动到子树大小超过 N2\frac N2 的子节点, 重复这一过程直到找到重心。

实现

import sys
# Increase recursion depth to handle maximum tree depth
sys.setrecursionlimit(200050)
maxn = 200010
n = 0
adj = [[] for _ in range(maxn)]
subtree_size = [0] * maxn

点分治

重点例题 – 继续学习之前,请先尽力独立解决这道题!

点分治是一种树上分治技巧。它反复在重心处分割树以及产生的各个子图,最终得到 O(log⁡N)\mathcal{O}(\log N) 层子图。

Resources
Carpanese

上题的解法

Tanuj Khattar

图解指南与例题讲解

robert1003

图解指南与例题

CF

上题的博客与视频,不过并不需要 LCA。

GFG
Warning!

以下实现来自 Carpanese ,其中第 20—21 行会因删除元素后使范围 for 循环的迭代器失效而导致段错误。 可以改为维护 is_removed 数组,并在访问子节点前检查它(下文采用此方法)。 另一种做法是改写 Carpanese 文章中的以下代码(第 3 行有问题):

for (auto v : tree[centroid])
tree[centroid].erase(v), // remove the edge to disconnect
tree[v].erase(centroid), // the component from the tree
build(v, centroid);

可以改写为:

for (auto v : tree[centroid]) {
tree[v].erase(centroid);
build(v, centroid);
}
tree[centroid].clear();

文章还给出了 O(log⁡2n)\mathcal{O}(\log^2n) 的更新复杂度,因为它假设计算节点到指定重心祖先 的距离还需 O(log⁡n)\mathcal{O}(\log n)。可以预处理这些距离(如下方代码所示),把更新 降至 O(log⁡n)\mathcal{O}(\log n),总复杂度降至 O((N+Q)log⁡n)\mathcal{O}((N+Q)\log n)。

实现

下面给出通用的点分治代码。

private static class Centroid {
int n;
int[][] g;
int[] size;
int[] parent;
boolean[] seen;
Centroid(int n, int[][] g) {
this.n = n;
this.g = g;

题解——Xenia & Tree

对每个节点,包含它的重心分量至多有 log⁡N\log N 个,其中 NN 是节点数。把这些分量 的重心称为该节点的重心祖先。树上任意两点之间的路径必经过二者的某个公共重心祖先, 因为树被分成了以各重心为根的子树。若为每个重心存储其到最近红点的距离,就可以 枚举一个节点的重心祖先,把“节点到该重心祖先的距离”与“该重心到最近红点的距离” 相加并取最小值,从而查询该节点到最近红点的距离。把节点染红时,只需更新它的全部 重心祖先。每个节点至多有 O(log⁡N)\mathcal{O}(\log N) 个重心祖先,所以两种操作都能在 O(log⁡N)\mathcal{O}(\log N) 时间内完成。

#include <bits/stdc++.h>
using namespace std;
// a number that is large enough while not causing overflow
const int INF = 1e9;
vector<vector<int>> adj;
vector<int> subtree_size;
// min_dist[v] := the minimal distance between v and a red node
vector<int> min_dist;

习题

StatusSourceProblem NameDifficultyTags
CFEasy
Show TagsCentroid
Baltic OIEasy
Show TagsCentroid, Small to Large
CSESEasy
Show TagsCentroid, Small to Large
CSESEasy
Show TagsBIT, Centroid
Old GoldEasy
Show TagsCentroid
IOIMedium
Show TagsCentroid, Merging
PlatinumMedium
Show TagsCentroid
CFMedium
Show TagsCentroid
CFMedium
Show TagsCentroid, Number Theory
CFMedium
Show TagsCentroid, DP
JOIMedium
Show TagsCentroid
COCIMedium
Show TagsCentroid, Hashing
DMOPCHard
Show TagsCentroid
Triway CupHard
Show TagsCentroid
JOIHard
Show TagsCentroid, Small to Large
PlatinumVery Hard
Show TagsCentroid

Module Progress: