Distance Queries - POJ 1986 LCA

本文介绍了一种结合最近公共祖先(LCA)算法解决路径长度查询问题的方法,通过具体实例展示了如何快速计算两点间的最短距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Distance Queries
Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 9314 Accepted: 3268
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. 

思路: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);
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值