我要懒死了,所以依然是lyd的课件截图
注意是min{max(max(d[uk]),dis(u1,ui),dis(uj,un))},每次都从这三个的max里取min
#include<iostream>
#include<cstdio>
using namespace std;
const int N=500005;
int n,m,h[N],cnt,d[N],s,t,mx,f[N],ans=1e9,q[N],tot,l,r;
bool v[N];
struct qwe
{int ne,to,va;
}e[N<<1];
int read()
{int r=0,f=1;char p=getchar();while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}
void add(int u,int v,int w)
{cnt++;e[cnt].ne=h[u];e[cnt].to=v;e[cnt].va=w;h[u]=cnt;
}
void dfs(int u,int fa,int len)
{f[u]=fa;if(len>mx)s=u,mx=len;for(int i=h[u];i;i=e[i].ne)if(e[i].to!=fa)d[e[i].to]=e[i].va,dfs(e[i].to,u,len+e[i].va);
}
int dfs1(int u,int fa)
{int mx=0;for(int i=h[u];i;i=e[i].ne)if(e[i].to!=fa&&!v[e[i].to])mx=max(mx,dfs1(e[i].to,u)+e[i].va);return mx;
}
int main()
{n=read(),m=read();for(int i=1;i<n;i++){int x=read(),y=read(),z=read();add(x,y,z),add(y,x,z);}dfs(1,0,0);t=s,mx=0,d[s]=0;dfs(s,0,0);for(int u=s;u;u=f[u])q[++tot]=u,d[f[u]]+=d[u],v[u]=1;//,cerr<<u<<" "<<d[u]<<endl;d[q[0]]=0;for(int i=tot;i>=1;i--)d[q[i]]=d[q[i-1]];// for(int i=0;i<=tot;i++)// cerr<<q[i]<<" "<<d[q[i]]<<endl;int mx=0;for(int i=1;i<=n;i++)mx=max(mx,dfs1(i,0));//cerr<<mx<<endl;for(int i=1;i<=tot;i++){l++;while(r<tot&&d[q[r+1]]-d[q[l]]<=m)r++;//cerr<<q[l]<<" "<<q[r]<<endl;ans=min(ans,max(mx,max(d[q[l]],d[q[tot]]-d[q[r]])));}printf("%d\n",ans);return 0;
}