题目链接:https://cn.vjudge.net/problem/HDU-2586
题意:求两点的距离
题解:tarjan求lca,学习:https://www.cnblogs.com/jsawz/p/6723221.html
#include<bits/stdc++.h>
using namespace std;
const int N=40010;
struct edge{
int to,nex,d;
}e1[N*2],e2[N*2];
int n,m;
int head1[N],head2[N];
int len1,len2;
int dis[N],vis[N],f[N];
int ans[N];
void init()
{
for(int i=1;i<=n;i++)
{
dis[i]=0;
head1[i]=-1;
head2[i]=-1;
vis[i]=0;
f[i]=i;
}
len1=0;
len2=0;
}
void addedge1(int x,int y,int z)
{
e1[len1].to=y;
e1[len1].d=z;
e1[len1].nex=head1[x];
head1[x]=len1++;
}
void addedge2(int x,int y,int z)
{
e2[len2].to=y;
e2[len2].d=z;
e2[len2].nex=head2[x];
head2[x]=len2++;
}
int fath(int x)
{
return f[x]==x?x:f[x]=fath(f[x]);
}
void dfs(int u)
{
vis[u]=1;
int to;
int x;
for(int i=head1[u];~i;i=e1[i].nex)
{
to=e1[i].to;
if(!vis[to])
{
dis[to]=dis[u]+e1[i].d;
dfs(to);
f[to]=fath(u);
}
}
for(int i=head2[u];~i;i=e2[i].nex)
{
to=e2[i].to;
if(vis[to])
{
x=fath(to);
ans[e2[i].d]=dis[u]+dis[e2[i].to]-2*dis[x];
}
}
}
int main()
{
int T;
int x,y,z;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
init();
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge1(x,y,z);
addedge1(y,x,z);
}
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
addedge2(x,y,i);
addedge2(y,x,i);
}
dfs(1);
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
return 0;
}