-
A -- How far away ?
- Description
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
- 题目理解
首先通过将一棵无根树转换为一棵以1号结点为根结点的树,通过邻接表存图,的时候记录父亲结点,对于当前结点的父亲结点跳过不进行处理,同时初始化深度和距离根结点的距离。对于跳跃结点的递推,因为,对应代码就是,由于是从、、...、所以首先初始化然后再去推,即相当于此后亦同,通过初始化数组由于访问到当前结点时前面所有的父亲结点都是已经赋值正确的,通过递推后面的值也会正确。得到深度和数组以后在进行。其原理就是对深度进行二进制查询,我们知道任意一个数都能够通过二进制表达,如果当前深度大于我们要跳跃的长度的时候我们进行跳跃赋值,否则就不进行跳跃。这样必须在同深度的情况下进行跳跃否则会交错得不到正确答案,有两种情况:
- 一个结点是另一个结点的祖先
- 两个结点互不为祖先关系
情况1在前面处理同深度的时候就会得到两个点重合的结果,这时候直接输出即可;
情况2两个结点同时通过二进制倍增最后长度缩短为(就像找零不会出现比、、...、还要长的长度),因为这时候再向上的结点必定相同,所以输出而不是
#include<cstdio>
#include<vector>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=40005;
struct ver{
int v,w;
ver(int V,int W):v(V),w(W){}
};
vector<ver> edge[maxn];
int dis[maxn],dep[maxn],f[maxn][20],k;
void dfs(int u,int fa,int deep){
dep[u]=deep;
for(int i=0;i<edge[u].size(); ++i){
int v=edge[u][i].v;
if(v==fa) continue;
dis[v]=dis[u]+edge[u][i].w;
f[v][0]=u;
int cur=0;
while(f[v][cur]!=1){
f[v][cur+1]=f[f[v][cur]][cur];
++cur;
}
dfs(v,u,deep+1);
}
return ;
}
int lca(int x,int y){
if(dep[x]<dep[y]) swap(x, y);
int i,lg;
for(lg=0;(1<<lg)<=dep[x];++lg);
--lg;
for(i=lg;i>=0;--i)
if(dep[x]-(1<<i)>=dep[y])
x=f[x][i];
if(x==y) return x;
for(i=lg;i>=0;--i)
if(f[x][i]!=f[y][i] )
x=f[x][i],y=f[y][i];
return f[x][0];
}
int main()
{
int t,n,m,u,v,w;
scanf("%d",&t);
while(t--){
for(int i=0;i<maxn;++i)edge[i].clear();
dis[1]=0,f[1][0]=1;
scanf("%d%d",&n,&m);
for(int i=1;i<n;++i){
scanf("%d%d%d",&u,&v,&w);
edge[u].push_back(ver(v,w));
edge[v].push_back(ver(u,w));
}
dfs(1,-1,1);
while(m--){
scanf("%d%d",&u,&v);
int fa=lca(u,v);
//printf("!!!%d\n",fa);
printf("%d\n",dis[u]+dis[v]-dis[fa]-dis[fa]);
}
}
return 0;
}