设置状态dp[u][2]
dp[u][0]表示距离u的最长距离,dp[u][1]表示距离u的次长距离(与最长距离的节点不在同一颗子树上)然后状态方程为
ans=(ans,dp[u][0]+dp[u][1])ans为树的直径答案
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;
const int maxn=100100;
struct EDGE
{
int v, w, next;
}e[maxn];
int cnt;
int head[maxn]={};
void Add(int u, int v, int w){
e[cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt ++;
}
int dp[2][maxn]={};
int n,s,ans;
void dfs(int u,int fa){
for(int i=head[u];i!=-1;i=e[i].next)if(e[i].v!=fa){
int v=e[i].v,w=e[i].w;
dfs(v,u);
if(dp[0][v]+w>dp[0][u]){
dp[1][u]=dp[0][u];
dp[0][u]=dp[0][v]+w;
}
else if(dp[0][v]+w>dp[1][u]) dp[1][u]=dp[0