[C++] syntaxhighlighter_viewsource syntaxhighlighter_copycode
#include<stdio.h>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<cstring>
#define N 600001
using namespace std;
int n,m,cnt,num,mmaxn;
int Last[N],End[2*N],Next[2*N],Cost[2*N],F[N][32],D[N],Sum[N][32],T[N],S[N],A[N],B[N],LC[N];
void add(int x,int y,int z){cnt++;End[cnt]=y;Next[cnt]=Last[x];Last[x]=cnt;Cost[cnt]=z;}
void DFS(int x,int f){
D[x]=D[F[x][0]]+1;
for(int i=1;i<=ceil(log2(D[x]));i++)F[x][i]=F[F[x][i-1]][i-1],Sum[x][i]=Sum[F[x][i-1]][i-1]+Sum[x][i-1];
for(int i=Last[x];i;i=Next[i]){
if(End[i]==f)continue;
F[End[i]][0]=x;Sum[End[i]][0]=Cost[i];
DFS(End[i],x);
}
}
int DDFS(int x){
int t=0;
for(int i=Last[x];i;i=Next[i]){
if(End[i]==F[x][0])continue;
t=max(DDFS(End[i]),t);
S[x]+=S[End[i]];
}
if(S[x]==num)t=max(t,Sum[x][0]);
return t;
}
int LCA(int x,int y,int id){
int tot=0;
if(D[x]<D[y])swap(x,y);
int k=D[x]-D[y],s=D[x];
for(int i=0;i<=ceil(log2(s));i++)if((1<<i)&k)tot+=Sum[x][i],x=F[x][i];
if(x==y){LC[id]=x;return tot;}
for(int i=ceil(log2(s));i>=0;i--)if(F[x][i]!=F[y][i])tot+=(Sum[x][i]+Sum[y][i]),x=F[x][i],y=F[y][i];
LC[id]=F[x][0];
return tot+Sum[x][0]+Sum[y][0];
}
bool Love(int limit){
memset(S,0,sizeof(S));num=0;
for(int i=1;i<=m;i++)if(T[i]>limit)S[A[i]]++,S[B[i]]++,S[LC[i]]-=2,num++;
int t=DDFS(1);
return mmaxn-t<=limit?true:false;
}
int main(){
int a,b,c,tot=0,l=0,r=0,mid,ans;
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++)scanf("%d%d%d",&a,&b,&c),add(a,b,c),add(b,a,c);
DFS(1,1);
for(int i=1;i<=m;i++)scanf("%d%d",&A[i],&B[i]),T[i]=LCA(A[i],B[i],i),r=max(T[i],r);
mmaxn=r;
while(l<=r){
mid=(l+r)>>1;
if(Love(mid))r=mid-1,ans=mid;
else l=mid+1;
}
printf("%d",ans);
}