Distance Queries - POJ 1986 LCA

来源:互联网 发布:腾讯手游助手mac 编辑:程序博客网 时间:2024/05/22 07:02

Distance Queries
Time Limit: 2000MS Memory Limit: 30000KTotal Submissions: 9314 Accepted: 3268Case 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 61 6 13 E6 3 9 E3 5 7 S4 1 3 N2 4 20 W4 7 2 S31 61 42 6

Sample Output

13336

Hint

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

思路:LCA加上距离的模板题。

AC代码如下:

#include<cstdio>#include<cstring>#include<vector>#include<algorithm>using namespace std;struct node{ int next,dis;};vector<node> G[100010];int root=1,parent[30][100010],depth[100010],dis[100010];char s[10];void dfs(int v,int p,int d){ parent[0][v]=p;  depth[v]=d;  int i,len=G[v].size();  for(i=0;i<len;i++)   if(G[v][i].next!=p)   { dis[G[v][i].next]=dis[v]+G[v][i].dis;     dfs(G[v][i].next,v,d+1);   }}void init(int V){ dfs(root,-1,0);  int k,v;  for(k=0;k+1<30;k++)   for(v=0;v<V;v++)    if(parent[k][v]<0)     parent[k+1][v]=-1;    else     parent[k+1][v]=parent[k][parent[k][v]];}int lca(int u,int v){ if(depth[u]>depth[v])   swap(u,v);  int k;  for(k=0;k<30;k++)   if((depth[v]-depth[u])>>k &1)    v=parent[k][v];  if(u==v)   return u;  for(k=29;k>=0;k--)   if(parent[k][u]!=parent[k][v])   { u=parent[k][u];     v=parent[k][v];   }  return parent[0][u];}int main(){ int n,m,i,j,k,u,v,d,len;  node A;  scanf("%d%d",&n,&m);  for(i=1;i<=m;i++)  { scanf("%d%d%d%s",&u,&v,&len,s);    A.dis=len;    A.next=u;    G[v].push_back(A);    A.next=v;    G[u].push_back(A);  }  init(n+2);  scanf("%d",&m);  for(i=1;i<=m;i++)  { scanf("%d%d",&u,&v);    d=lca(u,v);    printf("%d\n",dis[u]+dis[v]-dis[d]*2);  }}



0 0