解法一(On^3):https://blog.csdn.net/bjfu170203101/article/details/106337107
解法二(On^2):https://blog.csdn.net/bjfu170203101/article/details/106338373
解法三(Onlogm):https://blog.csdn.net/bjfu170203101/article/details/106339621
解法四/五(On):https://blog.csdn.net/bjfu170203101/article/details/106342984
显然选择的路径越长,偏心距越可能变小(因为路径上点多了,其他点到路径上点最大距离就会变小)
所以我们在直径上的点进行尺取优化。即可降到n^2
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ls (o<<1)
#define rs (o<<1|1)
#define pb push_back
const double PI= acos(-1.0);
const int M = 300+7;
int head[M],cnt;
void init(){cnt=0,memset(head,0,sizeof(head));}
struct EDGE{int to,nxt,w;}ee[M*2];
void add(int x,int y,int w){ee[++cnt].nxt=head[x],ee[cnt].w=w,ee[cnt].to=y,head[x]=cnt;}
int mx=0;
int p,q,f[M];
int d[M][M],rt,vs[M];
void dfs(int x,int fa,int sm)
{
if(sm>mx)mx=sm,p=x;
if(q)f[x]=fa;
d[rt][x]=sm;
for(int i=head[x];i;i=ee[i].nxt)
{
int y=ee[i].to,w=ee[i].w;
if(y==fa)continue;
dfs(y,x,sm+w);
}
}
bool flag;
void dfs2(int x,int fa,int sm)
{
if(flag)return ;
mx=max(sm,mx);//树上任意两点距离唯一,走非标记点所到达的点,一定是最近的
for(int i=head[x];i;i=ee[i].nxt)
{
int y=ee[i].to,w=ee[i].w;
if(y==fa||vs[y])continue;
dfs2(y,x,sm+w);
}
}
int main()
{
int n,s;
scanf("%d%d",&n,&s);
for(int i=1;i<n;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);add(v,u,w);
}
dfs(1,0,0);
vector<int>v;q=p;
mx=0;dfs(p,0,0);
while(p)
{
v.pb(p);
p=f[p];
}
for(int i=1;i<=n;i++)
{
rt=i;
dfs(i,0,0);
}
// cout<<"okk"<<" "<<p<<" "<<q<<endl;
int mi=1e9;
int i=0,j=0;
while(i<v.size())
{
while(d[v[i]][v[j]]<=s&&j<v.size())j++;
int x=v[i],y=v[j-1];
// cout<<x<<" "<<y<<endl;
if(d[x][y]>s)continue;
for(int k=i;k<j;k++)vs[v[k]]=1;
mx=0;
for(int k=i;k<j;k++)dfs2(v[k],0,0);
for(int k=i;k<j;k++)vs[v[k]]=0;
mi=min(mi,mx);
i++;
}
printf("%d\n",mi);
return 0;
}