1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| #include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <stack> #include <queue> #include <cmath> #include <set> #include <map> #define mp make_pair #define pb push_back #define pii pair<int,int> #define link(x) for(edge *j=h[x];j;j=j->next) #define inc(i,l,r) for(int i=l;i<=r;i++) #define dec(i,r,l) for(int i=r;i>=l;i--) const int MAXN=3e5+10; const double eps=1e-8; #define ll long long using namespace std; const int inf=1e9+10; struct edge{int t,v;edge*next;}e[MAXN<<1],*h[MAXN],*o=e; void add(int x,int y,int vul){o->t=y;o->v=vul;o->next=h[x];h[x]=o++;} ll read(){ ll x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); return x*f; } int n; int st[MAXN],tot,p[MAXN],dis[MAXN],s; bool vis[MAXN]; queue<int>que; int bfs(int x){ inc(i,1,n)dis[i]=vis[i]=0; vis[x]=1;que.push(x); while(!que.empty()){ int y=que.front();que.pop(); link(y)if(!vis[j->t])vis[j->t]=1,dis[j->t]=dis[y]+j->v,que.push(j->t); } int pos=x; inc(i,1,n)if(dis[pos]<dis[i])pos=i; return pos; } int sum[MAXN],fa[MAXN],ans[MAXN],key[MAXN]; void dfs(int x,int pre){ fa[x]=pre; link(x)if(j->t!=pre)sum[j->t]=sum[x]+j->v,key[j->t]=j->v,dfs(j->t,x); } void _dfs(int x,int y){ int k; if(vis[x])k=x;else k=y; p[x]=k; link(x)if(j->t!=fa[x])_dfs(j->t,k); } int maxx[MAXN<<2],R[MAXN]; void built(int x,int l,int r){ if(l==r){maxx[x]=ans[st[l]];return ;} int mid=(l+r)>>1; built(x<<1,l,mid); built(x<<1|1,mid+1,r); maxx[x]=max(maxx[x<<1],maxx[x<<1|1]); } int Maxx; void query(int x,int l,int r,int ql,int qr){ if(ql<=l&&r<=qr){Maxx=max(Maxx,maxx[x]);return ;} int mid=(l+r)>>1; if(ql<=mid)query(x<<1,l,mid,ql,qr); if(qr>mid)query(x<<1|1,mid+1,r,ql,qr); } int main(){ n=read();s=read(); int x,y,z; inc(i,2,n)x=read(),y=read(),z=read(),add(x,y,z),add(y,x,z); x=bfs(1);y=bfs(x); dfs(x,0);tot=0; inc(i,1,n)vis[i]=0; int k1=y; while(y)st[++tot]=y,vis[y]=1,y=fa[y]; y=k1; _dfs(x,x); inc(i,1,n)ans[p[i]]=max(ans[p[i]],sum[i]-sum[p[i]]); built(1,1,tot); inc(i,1,tot)R[i]=R[i-1]+key[st[i]]; int ans2=inf; inc(i,1,tot){ int l=i;int r=tot;int ans1=0; while(l<=r){ int mid=(l+r)>>1; if(R[mid]-R[i-1]<=s)ans1=mid,l=mid+1; else r=mid-1; } if(!ans1)ans1=i;else ans1=min(tot,ans1+1);
Maxx=0;query(1,1,tot,i,ans1); ans2=min(ans2,max(Maxx,max(sum[y]-sum[st[i]],sum[st[ans1]]-sum[x]))); } printf("%d\n",ans2); return 0; }
|