HDU2586 How far away ?(LCA板子题)
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.
InputFirst 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.OutputFor 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
这个题关于log的常数优化貌似不写也行,但最好还是写一下(洛谷那道模板不写的话会T两个点)
#include <bits/stdc++.h> #define N 50005 using namespace std; int n,m,t,tot=0,head[N],ver[2*N],edge[2*N],Next[2*N],f[N][22],d[N],dist[N],lg[50005];; void add(int x,int y,int z) { ver[++tot]=y,edge[tot]=z,Next[tot]=head[x],head[x]=tot; } void prework() { queue<int>q; q.push(1); d[1]=1; while(q.size()) { int x=q.front(); q.pop(); int i; for(i=head[x];i;i=Next[i]) { int y=ver[i],z=edge[i]; if(d[y])continue; d[y]=d[x]+1; dist[y]=dist[x]+z; f[y][0]=x;//y节点的2^0倍祖先是x int j; for(j=1;j<=lg[d[x]];j++) { f[y][j]=f[f[y][j-1]][j-1]; } q.push(y); } } } int lca(int x,int y) { if(d[x]<d[y])swap(x,y);//使得x深度较小 int i; while(d[x] > d[y]) { x = f[x][lg[d[x]-d[y]] - 1]; } if(x==y)return x; for(i=lg[d[x]] - 1;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; cin>>t; for(int i = 1; i <= 50005; ++i) lg[i] = lg[i-1] + (1 << lg[i-1] == i);//常数优化得放到循环外面 while(t--) { cin>>n>>m; int i; for(i=1;i<=n;i++)d[i]=head[i]=0; tot=0;//记得归零! for(i=1;i<=n-1;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); add(x,y,z); add(y,x,z); } prework(); for(i=1;i<=m;i++) { int a,b; scanf("%d%d",&a,&b); printf("%d\n",dist[a]+dist[b]-2*dist[lca(a,b)]); } } return 0; }