树的直径的结论:
1.所有直径相较于一点,且为边的中点。
2.以直径上一点为根的子树,深度不超过这一点到较近的端点的距离。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 500005;
const int maxm = 1000005;
int he[maxn],ver[maxm],ne[maxm],tot = 1;
LL cost[maxm];
void add( int x,int y,LL z ){
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
cost[tot] = z;
}
int s,t,fa[maxn];
LL d[maxn],mx;
void dfs(int x,int f){
for( int cure= he[x];cure;cure= ne[cure] ){
int y = ver[cure];
if(y==f) continue;
d[y] = d[x]+cost[cure];
fa[y] = (cure^1);
dfs(y,x);
if(d[y] > mx){
mx = d[y];
s = y;
}
}
}
int vis[maxn];
LL sum[maxn];
void dfs2( int x,int f ){
for( int cure = he[x];cure;cure= ne[cure] ){
int y = ver[cure];
if( y == f || vis[y] ) continue;
d[y] = d[x] + cost[cure];
mx = max(mx,d[y]);
dfs2(y,x);
}
}
int main(){
int n,x,y;
LL z,len;
scanf("%d%lld",&n,&len);
for( int i = 1;i < n;i++ ){
scanf("%d%d%lld",&x,&y,&z);
add(x,y,z);add(y,x,z);
}
d[1] = 0;
mx= 0 ;
dfs(1,0);
t =s;
mx = 0;
d[t] = 0;
dfs(t,0);
int num = 1;
fa[t] = 0;
for( int i = s;i;i = ver[fa[i]] ) {
vis[i] = 1;
d[i] = 0;
if(fa[i]){
num++;
sum[num] = sum[num-1]+cost[fa[i]];
}
}
mx = 0;
for( int i = s;i;i = ver[fa[i]] ){
dfs2(i,0);
}
int r = 1;
LL mn = 0x3f3f3f3f3f3f3f3f;
for( int l = 1;l <= num;l++ ){
while( r < l ||(r < num && sum[r+1] - sum[l] <=len) )r++;
mn= min(mn,max( sum[l],sum[num]-sum[r] ));
}
mx = max(mx,mn);
printf("%lld\n",mx);
return 0;
}