树形DP
树的最长路径
—就是找树的直径
情况1: 无权图
1. 任选一点u,求到该点最长路径的点p
2. 求到p最长路径的点q,pq之间的距离就是树的最长路径
算法证明: https://www.acwing.com/video/414/ 很巧妙hh可以回顾
情况2:有权图
1. 任选一个点,作为根结点(树中的所有点都可以作为根),向下拓展
2. dfs(root, father) 返回root向下的最长路径长 + 更新树的最长路径
3. father 记录每个点的父节点,根结点father=0,意思是没有父节点
code1
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e4 + 5, M = N * N;
int n;
int res = 0;
//1 无向图 边数是点数的接近两倍
// int h[N], e[N], ne[N], w[N], idx;
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c,h[a] = idx ++;
}
int dfs(int root, int father)
{
int d1, d2;
d1 = d2 = 0;
for(int i = h[root]; i != -1 ;i = ne[i]){
//2 v代表边权
int t = e[i], v = w[i];
if(t == father) continue;
int k = v + dfs(t, root);
//3 注意更新逻辑
// if(k > d1) d1 = k;
if(k > d1) d2 = d1, d1 = k;
else if(k > d2) d2 = k;
}
res = max(res, d1 + d2);
return d1;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for(int i = 0; i < n - 1; ++i){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
//4 无向图
add(b, a, c);
}
dfs(1, 0);
cout << res << endl;
}