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 109 110 111 112 113 114 115 116 117 118 119
| #include<bits/stdc++.h> using namespace std; typedef long long ll; #define N 300010 #define rep(i,l,r) for(int i=l;i<=r;++i) #define dow(i,l,r) for(int i=l;i>=r;--i) int e,head[N<<1],w[N<<1],last[N<<1],p[N]; int deep[N],fa[N],num[N],son[N]; int top[N]; int a[N],dis[N]; int u[N],v[N],lca[N],val[N]; int n,m; void add(int x,int y,int c) { head[++e]=y;w[e]=c; last[e]=p[x]; p[x]=e; } void dfs(int x,int pre,int dep) { deep[x]=dep; fa[x]=pre; num[x]=1; for(int j=p[x];j;j=last[j]) { int y=head[j]; if(y==pre) continue; dis[y]=dis[x]+w[j]; dfs(y,x,dep+1); num[x]+=num[y]; if(son[x]==-1||num[y]>num[son[x]]) son[x]=y; } } void dfs_son(int x,int rt) { top[x]=rt; if(son[x]==-1) return; else dfs_son(son[x],rt); for(int j=p[x];j;j=last[j]) if(head[j]!=fa[x] && head[j]!=son[x]) dfs_son(head[j],head[j]); } void dfs(int x) { for(int j=p[x];j;j=last[j]) { int y=head[j]; if(y==fa[x]) continue; dfs(y); a[x]+=a[y]; } } int calc(int x,int y) { int f1=top[x],f2=top[y]; while(f1!=f2) { if(deep[f1]<deep[f2]) { swap(x,y); swap(f1,f2); } x=fa[f1]; f1=top[x]; } if(deep[x]>deep[y]) swap(x,y); return x; }
bool ok(int mid) { int tot=0,mx=0,ans=0; memset(a,0,sizeof(a)); rep(i,1,m) if(val[i]>mid) { a[u[i]]++; a[v[i]]++; a[lca[i]]-=2; ++tot; ans=max(ans,val[i]); } dfs(1); rep(i,1,n) if(a[i]>=tot) mx=max(mx,dis[i]-dis[fa[i]]); return ans-mx<=mid; } int main() { scanf("%d%d",&n,&m); rep(i,1,n-1) { int x,y,c; scanf("%d%d%d",&x,&y,&c); add(x,y,c); add(y,x,c); } memset(son,-1,sizeof(son)); dfs(1,0,1); dfs_son(1,1); rep(i,1,m) { scanf("%d%d",u+i,v+i); lca[i]=calc(u[i],v[i]); val[i]=dis[u[i]]+dis[v[i]]-2*dis[lca[i]]; } int l=0,r=4e8; while(l<r) { int mid=(l+r)>>1; if(ok(mid)) r=mid; else l=mid+1; } printf("%d\n",l); return 0; }
|