题解:P10962 Computer
经典题,来写写题解。
原题链接
题意简述
给定一棵树,对于每个节点,输出它能到达的最远的距离。
题解
显然是换根 DP,但并不是那么好想。
钦定
- 一直向下走,即路径在
\operatorname{subtree}(u) 内; - 先向上走,再向下走到
\operatorname{subtree}(u) 之外的地方(下面直接称为向上走)。
对于第一种情况,我们容易通过一次 DFS 树形 DP 求出。
对于第二种情况,考虑使用换根 DP 求出每个节点向上走的最远距离。当从
- 若拐点为
u 的祖先,则这种情况已经在计算u 时被覆盖了,直接从v 走到u ,再累加上u 的向上走的最远距离; - 若拐点就是
u ,考虑令u 取到向下的最远距离的是哪个子树。- 如果不是
v 所在的子树,那么最长的路径必然是从v 走到u 后,在从u 向下走最长路; - 如果恰好是
v 所在的子树,那么走次长路即可。次长路可以在第一次树形 DP 时被求出。
- 如果不是
根据上述讨论,我们可以设计出这样的状态:设
对于第一次 DFS,转移是简单的:
对于第二次 DFS,我们按照上述讨论进行转移即可:
统计答案时,显然有
于是我们就轻松解决了本题,时间复杂度为
代码
// Problem: Computer
// Contest: HDOJ
// URL: https://acm.hdu.edu.cn/showproblem.php?pid=2196
// Memory Limit: 32 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <iostream>
#include <cstring>
using namespace std;
#define lowbit(x) ((x) & -(x))
#define add_mod(x, v) (x) = ((ll)(x) + (v)) % MOD
#define mul_mod(x, v) (x) = (1ll * (x) * (v)) % MOD
#define sub_mod(x, v) (x) = (((ll)(x) - (v)) % MOD + MOD) % MOD
typedef long long ll;
typedef pair<int, int> pii;
const int MAX_N = 1e4 + 5, MAX_M = 1e4 + 5;
int n, f[MAX_N][3], g[MAX_N];
struct AdjList {
int tot, head[MAX_N], nxt[MAX_M << 1], to[MAX_M << 1], edge[MAX_M << 1];
void init() {
tot = 0;
for (int i = 1; i <= n; ++i) head[i] = -1;
}
void insert(int x, int y, int z) {
to[++tot] = y;
edge[tot] = z;
nxt[tot] = head[x];
head[x] = tot;
}
} t;
void dfs1(int x, int fx) {
for (int i = t.head[x]; ~i; i = t.nxt[i]) {
int y = t.to[i], z = t.edge[i];
if (y == fx) continue;
dfs1(y, x);
if (f[x][0] < f[y][0] + z) {
f[x][1] = f[x][0];
f[x][0] = f[y][0] + z;
g[x] = y;
} else f[x][1] = max(f[x][1], f[y][0] + z);
}
}
void dfs2(int x, int fx) {
for (int i = t.head[x]; ~i; i = t.nxt[i]) {
int y = t.to[i], z = t.edge[i];
if (y == fx) continue;
f[y][2] = max(f[x][2], f[x][y == g[x]]) + z;
dfs2(y, x);
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
while (cin >> n) {
t.init();
for (int i = 2; i <= n; ++i) {
int j, w;
cin >> j >> w;
t.insert(i, j, w); t.insert(j, i, w);
}
memset(f, 0, sizeof(f));
memset(g, 0, sizeof(g));
dfs1(1, 0);
dfs2(1, 0);
for (int i = 1; i <= n; ++i) cout << max(f[i][0], f[i][2]) << '\n';
}
return 0;
}