桃花一簇开无主,可爱深红映浅红。
——《题百叶桃花》
桃花长在桃树上,树的每个节点有一个桃花,调皮的HtBest想摘尽可能多的桃花。HtBest有一个魔法棒,摘到树上任意一条链上的所有桃花,由于HtBest法力有限,只能使用一次魔法棒,请求出Htbest最多可以摘到多少个桃花。
桃花一簇开无主,可爱深红映浅红。
桃花长在桃树上,树的每个节点有一个桃花,调皮的HtBest想摘尽可能多的桃花。HtBest有一个魔法棒,摘到树上任意一条链上的所有桃花,由于HtBest法力有限,只能使用一次魔法棒,请求出Htbest最多可以摘到多少个桃花。
第一行有一个正整数n,表示桃树的节点个数。
接下来n-1行,第i行两个正整数ai,bi ,表示桃树上的节点ai,bi之间有一条边。
第一行一个整数,表示HtBest使用一次魔法棒最多可以摘到多少桃花。
3 1 2 2 3
3
3 1 2 1 3
3
4 1 2 2 3 3 4
4
对于100%的测试数据:
1 ≤ n ≤ 1000000
数据量较大,注意使用更快的输入输出方式。
private static int dfs(int a, int p) {
int max1 = 0; // 最高子树高度
int max2 = 0; // 次高子树高度
for (int i = head[a]; i > 0; i = nxt[i]) { // 遍历子树
int b = to[i];
if (b == p) continue; // 跳过父节点
int depth = dfs(b, a); // 子树高度
if (depth >= max1) { // 更新max1和max2(前两名可能同样高)
max2 = max1;
max1 = depth;
} else if (depth > max2) { // 更新max2
max2 = depth;
}
}
ans = Math.max(ans, max1 + max2 + 1); // 最大值
return max1 + 1; // 当前子树高度是最高子树高度+1
}