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
| #include<bits/stdc++.h> using namespace std; const int N = 5e5+10; int n,s,head[N],tot,dep[N],fa[N],a[N],cnt,d[N],Max,dis[N],vis[N],ans; struct e{ int next,to,w; } edge[N*2]; void add(int x,int y,int w){ edge[++tot].to = y; edge[tot].next = head[x]; edge[tot].w = w; head[x] = tot; } void dfs(int u,int fat){ vis[u] = 1; Max = max(Max,dep[u]); fa[u] = fat; int v; for (int i=head[u];i;i = edge[i].next){ v = edge[i].to; if (vis[v]) continue; dep[v] = dep[u]+edge[i].w; dfs(v,u); } } void getdia(){ dfs(1,0); int mpos = 1; for (int i=2;i<=n;i++) if (dep[mpos]<dep[i]) mpos = i; dep[mpos] = 0; memset(vis,0,sizeof(vis)); dfs(mpos,0); for (int i=1;i<=n;i++) if (dep[mpos]<dep[i]) mpos = i; while (mpos){ d[++cnt] = mpos; dis[cnt] = dep[d[cnt]]; mpos = fa[mpos]; } memset(vis,0,sizeof(vis)); Max = -1; ans = 0x3f3f3f3f; for (int i=1;i<=cnt;i++) vis[d[i]] = 1; int l = 1; for (int i=1;i<=cnt;i++){ while (dis[l]-dis[i]>s) l++; dep[d[i]] = 0; dfs(d[i],0); ans = min(ans,max(dis[1]-dis[l],max(dis[i]-dis[cnt],Max))); } cout<<ans<<endl; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n>>s; int x,y,z; for (int i=1;i<n;i++){ cin>>x>>y>>z; add(x,y,z); add(y,x,z); } getdia(); return 0; }
|