#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
struct edge{
int to,nxt,val;
}d[N]; int head[N],cnt=1;
void add(int u,int v,int k){ d[++cnt]=(edge){v,head[u],k},head[u]=cnt; }
int n,m,son[N],siz[N],deep[N],fa[N][20],an[N];
int top[N];
void dfs(int u,int father,int depth){
siz[u]=1,deep[u]=depth,fa[u][0]=father;
int maxson=-1;
for(int i=head[u];i;i=d[i].nxt ){
int v=d[i].to;
if( v==father ) continue;
dfs(v,u,depth+1);
siz[u]+=siz[v];
if( maxson<siz[v] ) maxson=siz[v],son[u]=v;
}
}
void dfs2(int x,int t){
top[x]=t;
if(son[x]==0) return ;
dfs2(son[x],t);
for(int i=head[x];i;i=d[i].nxt){
int v=d[i].to;
if(v!=son[x]&&v!=fa[x][0]) dfs2(v,v);
}
}
int query(int a,int b){
while(top[a]!=top[b]){
if(deep[top[a]]>deep[top[b]]){
a=fa[top[a]][0];
}else{
b=fa[top[b]][0];
}
}
return deep[a]>deep[b]?b:a;
}
int dis[N];
void dfs3(int x,int fa){
for(int i=head[x];i;i=d[i].nxt){
int v=d[i].to,val=d[i].val;
if(v==fa) continue;
dis[v]=dis[x]+val;
// cout<<val<<endl;
dfs3(v,x);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++){
int a,b,k;scanf("%d%d%d",&a,&b,&k);
add(a,b,k);add(b,a,k);
}
dfs(1,0,1);dfs2(1,1);dfs3(1,0);
// cout<<dis[2]<<endl;
// int q;scanf("%d",&q);
while(m--){
int a,b;scanf("%d%d",&a,&b);
int lcapos=query(a,b);
printf("%d\n",dis[a]+dis[b]-2*dis[lcapos]);
}
}
1556:Dis(lca+前缀和
最新推荐文章于 2022-12-20 16:33:59 发布