题意:给棵树询问树上两点距离
lca 板子
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define lim 80500
using namespace std;
int T,n,m,tot;
int f[lim][31],v[lim],c[lim],head[lim],nextt[lim],dist[lim],depth[lim];
void add_edge(int x,int y,int z){v[++tot]=y;c[tot]=z;nextt[tot]=head[x];head[x]=tot;}
void init()
{
for (int i=0;i<=n;i++)
{
tot=0;c[i]=0;v[i]=0;head[i]=0;nextt[i]=0;dist[i]=0;depth[i]=0;
for (int j=0;j<31;j++) f[i][j]=0;
}
}
void dfs(int x,int g)
{
for (int i=head[x];i;i=nextt[i])
{
int y=v[i];
if (y!=g)
{
depth[y]=depth[x]+1;
dist[y]=dist[x]+c[i];
f[y][0]=x;
for (int j=1;j<31;j++) f[y][j]=f[f[y][j-1]][j-1];
dfs(y,x);
}
}
}
int lca(int x,int y)
{
if (depth[x]<depth[y]) swap(x,y);
int d=depth[x]-depth[y];
for (int i=0;i<31;i++)
if (d&(1<<i)) x=f[x][i];
for (int i=30;i>=0;i--)
if (f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
return (x==y?x:f[x][0]);
}
int main()
{
scanf("%d",&T);
while(T--)
{
int x,y,z;
scanf("%d%d",&n,&m);
init();
for (int i=0;i<n-1;i++)
{
scanf("%d%d%d",&x,&y,&z);
add_edge(x,y,z);add_edge(y,x,z);
}
dfs(1,0);
for (int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
printf("%d\n",(dist[x]+dist[y])-2*dist[lca(x,y)]);
}
}
return 0;
}