There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.
Sample Input
2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1
Sample Output
10 25 100 100
思路:
问一棵树上,某两个结点的距离,其实可以用最近公共祖先来解,假设根节点为D,查询A、B两点,他们的最近公共祖先为C,这道题目求解,就是用这个公式|AB|=|AD|+|BD|-2*|CD|。
这里用的是离线的tarjan算法。(博客)
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<string.h>
#define mod (1000000007)
#define ll long long
#define ull unsigned long long
using namespace std;
struct node{
int to;
int w;
int nex;
}side[1010101];
struct nod{
int id,x,y,w;
}que[10101];
int head[101010];
int vis[101010];
int dis[101001];
int cnt=0,tot=0;
int f[50010];
int n,m;
int getf(int x)
{
if(f[x]!=x)
f[x]=getf(f[x]);
return f[x];
}
void init()
{
for(int i=0;i<50000;i++)
f[i]=i;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
cnt=0;
tot=0;
}
void add(int x,int y,int w)
{
side[cnt].to=y;
side[cnt].nex=head[x];
side[cnt].w=w;
head[x]=cnt++;
}
void lca(int x,int ff)
{
for(int i=head[x];i!=-1;i=side[i].nex)
{
int ty=side[i].to;
if(ty==ff)
continue;
dis[ty]=dis[x]+side[i].w;//x不是ff
lca(ty,x);
}
for(int i=0;i<m;i++)
{
if(que[i].x==x)
{
if(vis[que[i].y])
{
que[i].w=getf(que[i].y);
}
}
else if(que[i].y==x)
{
if(vis[que[i].x])
{
que[i].w=getf(que[i].x);
}
}
}
vis[x]=1;
f[x]=ff;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
init();
scanf("%d%d",&n,&m);
for(int i=0;i<n-1;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
for(int i=0;i<m;i++)
{
scanf("%d%d",&que[i].x,&que[i].y);//也可以开个邻接表存,并且记录下id,最后查询时开一个一维数组,把找到的公共祖先存放到一维数组中这两个点的id的位置,最后直接遍历一遍数组就好
que[i].id=i;
}
lca(1,1);
for(int i=0;i<m;i++)
{
printf("%d\n",dis[que[i].x]+dis[que[i].y]-2*dis[que[i].w]);
}
}
return 0;
}