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.
* 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.
题意:输入n,m,紧接着输入m行,每一行有四个数,分别表示A,B,A、B之间的距离,方向
然后再输入一个t,接下来有t行,每一行输入两个数,输出两点之间的最短距离
F1——(13)——F6——(9)——F3
|
(3)
|
F4——(20)——F2
|
(2)
|
F7
使用LCA算法,首先考虑没对点的最短路径的计算,如果确定一个根root,那么有dist(u,v)=dist(root,u)+dist(root,v)-2*dist(root,LCA(u,v));也就是说可以从根做一次深度优先遍历求出每个点到根节点的距离,再做一次LCA,对于每对询问,只要最近公共祖先求出来了,那个两点之间的距离就可以按照上面所说的方式计算
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int M=80005;
int p[M],head[M],vis[M],headq[M],dist[M],ans[M];
int a1,a2;
struct node
{
int to;
int next;
int len;
}Node[M],qNode[M];
void add_1(int x,int y,int len)
{
Node[a1].to=y;
Node[a1].len=len;
Node[a1].next=head[x];
head[x]=a1++;
}
void add_2(int x,int y,int len)
{
qNode[a2].next=headq[x];
qNode[a2].to=y;
qNode[a2].len=len;
headq[x]=a2++;
}
int find(int x)
{
if(p[x]!=x)
p[x]=find(p[x]);
return p[x];
}
void lca(int u,int now)
{
dist[u]=now;
int k;
vis[u]=1;
for(k=head[u];k!=-1;k=Node[k].next)
{
int v=Node[k].to;
int w=Node[k].len;
if(!vis[v])
{
lca(v,now+w);
p[v]=u;
}
}
for(k=headq[u];k!=-1;k=qNode[k].next)
{
int v=qNode[k].to;
int w=qNode[k].len;
if(vis[v])
{
ans[w]=dist[u]+dist[v]-2*dist[find(v)];
}
}
}
int main()
{
int n,m;
int a,b,len;
char fx;
while(cin>>n>>m)
{
memset(vis,0,sizeof(vis));
memset(head,-1,sizeof(head));
memset(headq,-1,sizeof(headq));
for(int i=0;i<n+1;i++)
p[i]=i;
a1=1;
a2=1;
for(int i=0;i<m;i++)
{
cin>>a>>b>>len>>fx;
add_1(a,b,len);
add_1(b,a,len);
}
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
cin>>a>>b;
add_2(a,b,i);
add_2(b,a,i);
}
lca(1,0);
for(int i=1;i<=t;i++)
cout<<ans[i]<<endl;
}
return 0;
}