Link
meaning of problems:
seeking the edge weight diameter (longest chain tree) of n tree
ideas:
firstly that the root optionally, referred to as \ (the root \) and Hutchison \ (dp [x] \) is to \ ( X \) starting its downward path with the maximum of all the nodes
for a tree the DP
\ (DP [I] = \ max \ limits_ {J \ in Son (I)} (DP [I], W [I] [ j] + dp [j])
\) we can see that in fact the diameter of the tree is the maximum value and the second largest value and the starting point of a path length, and the two side paths are not repeated
we performed tree DP on transition from the lower to \ (RES \) is updated:
\ (RES = \ max \ limits_ {J \ in Son (I)} (RES, DP [I] + DP [J] + W [I] [ j]) \)
Code:
#include<iostream>
using namespace std;
const int N=4e4+5;
const int M=8e4+5;
int n,m;
int cnt;
int to[M],val[M],nxt[M],head[N];
bool st[N];
int dp[N];
int res;
void addedge(int u,int v,int w) {
cnt++;
to[cnt]=v;
val[cnt]=w;
nxt[cnt]=head[u];
head[u]=cnt;
}
void dfs(int u) {
st[u]=true;
for(int i=head[u];i;i=nxt[i]) {
int v=to[i],w=val[i];
if(st[v]) continue;
dfs(v);
res=max(res,dp[u]+dp[v]+w);
dp[u]=max(dp[u],dp[v]+w);
}
}
int main() {
//freopen("in.txt","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++) {
int u,v,w;
char c;
cin>>u>>v>>w>>c;
addedge(u,v,w);
addedge(v,u,w);
}
dfs(1);
cout<<res<<endl;
return 0;
}