看到题目,可以发现比较像 dp。 设 fuf_ufu 表示 uuu 到 uuu 子树里的关键点的距离最大值,gug_ugu 表示 uuu 到 uuu 子树外的关键的的距离最大值。 可以得出状态转移方程。 fu={max(0,maxv∈sonufv+1) u is a key pointmaxv∈sonufv+1 otherwisef_u=\left\{ \begin{aligned} \max(0,\max_{v\in son_u}f_v+1)&\ \ \ \ \text{u is a key point}\\ \max_{v\in son_u}f_v+1 &\ \ \ \ \text{otherwise} \end{aligned} \right.fu=⎩⎨⎧max(0,v∈sonumaxfv+1)v∈sonumaxfv+1 u is a key point otherwise gu={max(0,gfau+1,maxv∈brotherufv+2) u is a key pointmax(gfau+1,maxv∈brotherufv+2) otherwiseg_u=\left\{ \begin{aligned} \max(0,g_{fa_u}+1,\max_{v\in brother_u}f_v+2)&\ \ \ \ \text{u is a key point}\\ \max(g_{fa_u}+1,\max_{v\in brother_u}f_v+2) &\ \ \ \ \text{otherwise} \end{aligned} \right.gu=⎩⎨⎧max(0,gfau+1,v∈brotherumaxfv+2)max(gfau+1,v∈brotherumaxfv+2) u is a key point otherwise 然后根据换根 dp 老套路,记录每个点的兄弟节点,跑两边 DFS 即可,时间复杂度 O(n)O(n)O(n)。