Problem 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
数据结构-LCA(树链剖分)
用树链剖分的方式求LCA,用edg数组保留点到父结点的距离,dis数组保存点到top结点的距离,在求LCA的过程中求出答案
点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e5;
int h[N],e[N],ne[N],c[N],idx;
int s[N],d[N],f[N],son[N],top[N],dis[N],edg[N];
void add(int u,int v,int w)
{
e[++idx]=v;
ne[idx]=h[u];
c[idx]=w;
h[u]=idx;
}
void dfs1(int x,int fa,int w)
{
s[x]=1;d[x]=d[fa]+1;
son[x]=0;f[x]=fa;edg[x]=w;
for(int i=h[x];~i;i=ne[i])
{
int j=e[i];
if(j==fa) continue;
dfs1(j,x,c[i]);
s[x]+=s[j];
if(s[son[x]]<s[j]) son[x]=j;
}
}
void dfs2(int x,int t)
{
top[x]=t;
if(x!=t)
dis[x]=dis[f[x]]+edg[x];
if(son[x]!=0) dfs2(son[x],t);
for(int i=h[x];~i;i=ne[i])
{
int j=e[i];
if(j!=f[x]&&j!=son[x]) dfs2(j,j);
}
}
int lca(int u,int v)
{
int ans=0;
while(top[u]!=top[v])
{
if(d[u]<d[v]) swap(u,v);
ans+=dis[u]+edg[top[u]];
u=f[top[u]];
}
ans+=abs(dis[u]-dis[v]);
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int T;
cin>>T;
while(T--)
{
memset(h,-1,sizeof h);
idx=0;
int n,m;
cin>>n>>m;
for(int i=0;i<n-1;++i)
{
int u,v,w;
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
dfs1(1,0,0);
dfs2(1,1);
for(int i=0;i<m;++i)
{
int a,b;
cin>>a>>b;
cout<<lca(a,b)<<'\n';
}
}
}