树的直径 二分
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 500005
#define F inline
using namespace std;
struct edge{ int next,to,dis; }ed[N<<1];
int n,m,k,s,t,l,r,num,sum[N],h[N],que[N],pre[N],dis[N];
bool f[N];
F char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
F int _read(){
int x=0; char ch=readc();
while (!isdigit(ch)) ch=readc();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x;
}
F void addedge(int x,int y,int z){
ed[++k]=(edge){h[x],y,z},h[x]=k;
}
F int bfs(int s){
memset(f,false,sizeof(f));
int r=0,w=1,ret=s; que[1]=s,f[s]=true,dis[s]=0;
while (r<w){
int x=que[++r];
for (int i=h[x],v;i;i=ed[i].next)
if (!f[v=ed[i].to]){
dis[v]=dis[x]+ed[i].dis;
pre[v]=i^1,f[que[++w]=v]=true;
if (dis[ret]<dis[v]) ret=v;
}
}
return ret;
}
void dfs(int x,int p,int t,int rem){
l=max(l,rem);
for (int i=h[x],v;i;i=ed[i].next)
if ((v=ed[i].to)!=p&&v!=t)
dfs(v,x,x,rem+ed[i].dis);
}
F void doit(){
int x=t,p=0,tem[N]; num=1;
while (x!=s){
sum[++num]=ed[pre[x]].dis;
dfs(x,p,ed[pre[x]].to,0),p=x;
x=ed[pre[x]].to;
}
dfs(s,s,p,0); for (int i=2;i<=num;i++) tem[i]=sum[num-i+2];
for (int i=2;i<=num;i++) tem[i]+=tem[i-1];
for (int i=1;i<=num;i++) sum[i]=tem[i]; r=sum[num];
}
F bool pd(int mx){
int p=1,q=1;
while (sum[p]<=mx&&p<=num) p++;
q=--p;
while (sum[q]-sum[p]<=m&&q<=num) q++;
return sum[num]-sum[q-1]<=mx;
}
int main(){
n=_read(),m=_read(),k=1;
for (int i=1,x,y,z;i<n;i++){
x=_read(),y=_read(),z=_read();
addedge(x,y,z),addedge(y,x,z);
}
s=bfs(1),t=bfs(s);
doit(); int mid;
while (l!=r)
if (pd(mid=l+r>>1)) r=mid;
else l=mid+1;
return printf("%d\n",l),0;
}