POJ.1986 Distance Queries ( LCA 倍增 )
题意分析
给出一个N个点,M条边的信息(u,v,w),表示树上u-v有一条边,边权为w,接下来有k个询问,每个询问为(a,b),求a,b两点到lca(a,b)的边权之和为多少。
倍增维护树上前缀和,求得LCA之后,相应做差即可。
代码总览
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define nmax 80520
#define demen 25
using namespace std;
int fa[nmax][demen],dis[nmax],head[nmax],dep[nmax];
int n,m,tot = 0;
struct node{
int to;
int next;
int w;
}edge[nmax];
void add(int u, int v, int w){
edge[tot].to = v;
edge[tot].next = head[u];
edge[tot].w = w;
head[u] = tot++;
}
void dfs(int rt,int f){
fa[rt][0] = f;
for(int i = 1;i<=20;++i){
fa[rt][i] = fa[fa[rt][i-1]][i-1];
}
for(int i = head[rt];i!=-1;i = edge[i].next){
int nxt = edge[i].to;
if(nxt != f){
dis[nxt] = dis[rt] + edge[i].w;
dep[nxt] = dep[rt] + 1;
dfs(nxt,rt);
}
}
}
int lca(int x, int y){
int X = x,Y=y;
if(dep[x] < dep[y]) swap(x,y);
for(int i = 20;i>=0;--i){
if(dep[y] <= dep[fa[x][i]])
x = fa[x][i];
}
if(x == y) return(abs(dis[X] - dis[Y]));
for(int i = 20;i>=0;--i){
if(fa[x][i] != fa[y][i]){
x = fa[x][i],y = fa[y][i];
}
}
return(dis[X]+dis[Y] - 2*dis[fa[x][0]]);
}
void init(){
memset(fa,0,sizeof fa);
memset(head,-1,sizeof head);
memset(dis, 0, sizeof dis);
memset(dep,0,sizeof dep);
tot = 0;
}
int main()
{
while(scanf("%d %d",&n,&m) != EOF){
init();
int u,v,w,x,y;
char c;
for(int i = 0;i<m;++i){
scanf("%d %d %d %c",&u,&v,&w,&c);
add(u,v,w);
add(v,u,w);
}
dep[1] = 1;
dfs(1,0);
int k = 0; scanf("%d",&k);
for(int i = 0;i<k;++i){
scanf("%d %d",&x,&y);
printf("%d\n",lca(x,y));
}
}
return 0;
}