例题:http://poj.org/problem?id=1986
POJ1986 Distance Queries
Language:
Default Distance Queries
Description Farmer John's cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in "Navigation Nightmare",followed by a line containing a single integer K, followed by K "distance queries". Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ's distance queries as quickly as possible!
Input * Lines 1..1+M: Same format as "Navigation Nightmare"
* Line 2+M: A single integer, K. 1 <= K <= 10,000 * Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms. Output * Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.
Sample Input 7 6 Sample Output 13 Hint Farms 2 and 6 are 20+3+13=36 apart.
|
带权值的LCA处理方法和原处理方法唯一一点区别就是加了一个数组step[x]用来记录到根节点的距离,最后step[x]+step[y]-2*step[point]其中point为x和y的最近公共祖先点
AC代码:
#include<cstdio>
#include<vector>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1e5+;
ll bits[];
ll depth[N];
int fa[N][];
struct stu {
int a,b;
};
vector<stu>ve[N];
int n,m;
int mark[N];
ll step[N];
void inint(){
bits[]=;
for(int i=;i<=;i++)
bits[i]=bits[i-]<<;
} void dfs(int x,int y){
depth[x]=depth[y]+;
fa[x][]=y;
for(int i=;i<ve[x].size();i++){
if(ve[x][i].a==y){
step[x]=step[y]+ve[x][i].b;
}
}
for(int i=;i<;i++) fa[x][i]=fa[fa[x][i-]][i-];
for(int i=;i<ve[x].size();i++){
int x1=ve[x][i].a;
if(x1!=y){
dfs(x1,x);
}
}
} int lca(int x,int y){ if(depth[x]<depth[y]) swap(x,y);
int dif=depth[x]-depth[y];
for(int i=;i>=;i--){
if(dif>=bits[i]){
x=fa[x][i];
dif-=bits[i];
}
}
if(x==y) return x;
for(int i=;i>=;i--){
if(depth[x]>=bits[i]&&fa[x][i]!=fa[y][i]){
x=fa[x][i];
y=fa[y][i];
}
}
return fa[x][];
}
int main(){
inint();
scanf("%d%d",&n,&m);
int x,y,z;
for(int i=;i<=m;i++){
scanf("%d%d%d",&x,&y,&z);
getchar();getchar();
ve[x].push_back({y,z});
ve[y].push_back({x,z});
}
dfs(,);
int d;
scanf("%d",&d);
while(d--){
int x1,y1;
scanf("%d%d",&x1,&y1);
int point=lca(x1,y1);
printf("%d\n",step[x1]+step[y1]-*step[point]);
}
return ;
}