1、B站视频链接:E34 树形DP 树的中心_哔哩哔哩_bilibili
#include <bits/stdc++.h>
using namespace std;
const int N=20010;
int n,a,b,c,ans=2e9;
struct edge{int v,w;};
vector<edge> e[N];
int d1[N],d2[N],path[N],up[N];//path记录d1
void dfs1(int x,int fa){
for(auto ed:e[x]){
int y=ed.v,z=ed.w;
if(y==fa)continue;
dfs1(y,x);
if(d1[y]+z>d1[x]){
d2[x]=d1[x],d1[x]=d1[y]+z,path[x]=y;
}else if(d1[y]+z>d2[x])d2[x]=d1[y]+z;
}
}
void dfs2(int x,int fa){
for(auto ed:e[x]){
int y=ed.v,z=ed.w;
if(y==fa)continue;
if(y==path[x])up[y]=max(up[x],d2[x])+z;
else up[y]=max(up[x],d1[x])+z;
dfs2(y,x);
}
}
int main(){
cin>>n;
for(int i=1;i<n;i++){
cin>>a>>b>>c;
e[a].push_back({b,c});
e[b].push_back({a,c});
}
dfs1(1,0);//向下
dfs2(1,0);//向上
for(int i=1;i<=n;i++){
ans=min(ans,max(d1[i],up[i]));
}
cout<<ans;
return 0;
}