POJ1986 Distance Queries (LCA)(倍增)

时间:2020-12-06 13:48:34
Distance Queries
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 12950   Accepted: 4577
Case Time Limit: 1000MS

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
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
3
1 6
1 4
2 6

Sample Output

13
3
36

Hint

Farms 2 and 6 are 20+3+13=36 apart.

Source

【分析】给你一棵树及其边权,求给定的两个点之间的距离。可用一下在线LCA的做法,找公共祖先,求距离。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#define inf 10000000000000
#define met(a,b) memset(a,b,sizeof a)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
using namespace std;
const int N = 3e6+;
const int M = 4e5+;
int n,m,k,tot=;
int fa[N][],head[N],dis[N],dep[N];
struct man{
int to,next,w;
}edg[N];
void add(int u,int v,int w){
edg[tot].to=v;edg[tot].next=head[u];edg[tot].w=w;head[u]=tot++;
}
void dfs(int u,int f){
fa[u][]=f;
for(int i=;i<;i++){
fa[u][i]=fa[fa[u][i-]][i-];
}
for(int i=head[u];i!=-;i=edg[i].next){
int v=edg[i].to;
if(v!=f){
dis[v]=dis[u]+edg[i].w;
dep[v]=dep[u]+;
dfs(v,u);
}
}
}
int lca(int u,int v){
int U=u,V=v;
if(dep[u]<dep[v])swap(u,v);
for(int i=;i>=;i--){
if(dep[fa[u][i]]>=dep[v]){
u=fa[u][i];
}
}
if(u==v)return (abs(dis[U]-dis[V]));
for(int i=;i>=;i--){
if(fa[u][i]!=fa[v][i]){
u=fa[u][i];v=fa[v][i];
}
}
return (dis[U]+dis[V]-*dis[fa[u][]]);
}
int main(){
met(head,-);
scanf("%d%d",&n,&m);
char str[];
int u,v,w;
while(m--){
scanf("%d%d%d",&u,&v,&w);
scanf("%s",str);
add(u,v,w);add(v,u,w);
}
dep[]=;
dfs(,);
scanf("%d",&k);
while(k--){
scanf("%d%d",&u,&v);
printf("%d\n",lca(u,v));
}
return ;
}