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
| #include <bits/stdc++.h> #define MAXN 100005 using namespace std;
int n, k, maxlen, maxdis, root, l, r, cnt, head[MAXN], son1[MAXN], son2[MAXN], dis[MAXN], tag[MAXN], vis1[MAXN], vis2[MAXN];
struct Edge {int next, to, dis;} edge[MAXN*2];
void addedge(int x, int y, int z) { edge[++cnt].next=head[x]; edge[cnt].to=y; edge[cnt].dis=z; head[x]=cnt; }
int findline(int x, int fa) { int len1=0, len2=0; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa) continue; int len=findline(to, x)+edge[i].dis; if(len>=len2) len2=len, son2[x]=i; if(len2>len1) swap(len2, len1), swap(son1[x], son2[x]); } if(len1+len2>maxlen) maxlen=len1+len2, root=x; return len1; }
void finddis(int x, int fa) { for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==fa || tag[to]) continue; finddis(to, x); dis[x]=max(dis[x], edge[i].dis+dis[to]); } for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(!tag[to] || to==fa) continue; finddis(to, x); } maxdis=max(maxdis, dis[x]); }
int solve(int l, int r) { int ans=1e9, ldis=0, rdis=maxlen, x=l, y=l; for(int i=1; i<k; i++) { for(int j=head[y]; j; j=edge[j].next) { int to=edge[j].to; if(!tag[to] || vis1[to]) continue; rdis-=edge[j].dis; vis1[y]=1; y=to; } } ans=min(ans, max(rdis, ldis)); while(y!=r) { for(int j=head[y]; j; j=edge[j].next) { int to=edge[j].to; if(!tag[to] || vis1[to]) continue; rdis-=edge[j].dis; vis1[y]=1; y=to; } for(int j=head[x]; j; j=edge[j].next) { int to=edge[j].to; if(!tag[to] || vis2[to]) continue; ldis+=edge[j].dis; vis2[x]=1; x=to; }
ans=min(ans, max(rdis, ldis)); } return max(ans, maxdis); }
int main() { scanf("%d%d", &n, &k); for(int i=1; i<n; i++) { int x, y, z; scanf("%d%d%d", &x, &y, &z); addedge(x, y, z); addedge(y, x, z); } findline(1, 0); tag[root]=1; l=r=root; for(int i=son1[root]; i; i=son1[edge[i].to]) tag[edge[i].to]=1, l=edge[i].to; for(int i=son2[root]; i; i=son1[edge[i].to]) tag[edge[i].to]=1, r=edge[i].to; finddis(root, 0); printf("%d\n", solve(l, r)); }
|