欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Distance Queries POJ - 1986(最近公共祖先)

程序员文章站 2022-05-27 16:15:11
...
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.
题意:题目大意:John是一个农场主,他的牛很懒,拒绝按照John选的路走。John不得不找一条

最短的路。这道题的输入前半部分和POJ1984"Navigation Nightmare"相同。在每组数据之后是一个整数K,接下来K行是询问(u,v)的曼哈顿距离(u,v是农场编号)。最后输出所有询问结果。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 40010;
const int M = 20010;
struct node{
	int u,v,w;
	int lca;
	int next;
}edge1[N*2],edge2[M];
int id1,id2,head1[N],head2[N];
int ance[N],per[N],vis[N],dir[N];
int n,m;
void add1(int u,int v,int w){
	edge1[id1].u=u;
	edge1[id1].v=v;
	edge1[id1].w=w;
	edge1[id1].next=head1[u];
	head1[u]=id1++;
}
void add2(int u,int v){
	edge2[id2].u=u;
	edge2[id2].v=v;
	edge2[id2].lca=-1;
	edge2[id2].next=head2[u];
	head2[u]=id2++;
}
void init(){
	id1=id2=0;
	memset(head1,-1,sizeof(head1));
	memset(head2,-1,sizeof(head2));
	memset(dir,0,sizeof(dir));
	memset(vis,0,sizeof(vis));
}
int Find(int x){
	if(x == per[x]) return x;
	return per[x] = Find(per[x]);
}
void tarjan(int u){
	ance[u]=per[u]=u;
	vis[u]=1;
	for(int i=head1[u];i!=-1;i=edge1[i].next){
		int v=edge1[i].v, w=edge1[i].w;
		if(!vis[v]){
			dir[v]=dir[u]+w;
			tarjan(v);
			per[v]=u;
		}
	}
	for(int i=head2[u];i!=-1;i=edge2[i].next){
		int v=edge2[i].v;
		if(vis[v]){
			edge2[i].lca = edge2[i^1].lca = ance[Find(v)];
		}
	}
}
int main(){
	while(scanf("%d%d",&n,&m) != EOF){
		init();
		for(int i=0;i<m;i++){
			int u,v,w;
			char str[10];
			scanf("%d%d%d%s",&u,&v,&w,str);
			add1(u,v,w);
			add1(v,u,w);
		}
		int c;
		scanf("%d",&c);
		for(int i=0;i<c;i++){
			int u,v;
			scanf("%d%d",&u,&v);
			add2(u,v);
			add2(v,u);
		}
		tarjan(1);
		for(int i=0;i<c;i++){
			int id=i*2;
			int u=edge2[id].u,v=edge2[id].v,lca=edge2[id].lca;
			printf("%d\n",dir[u]+dir[v]-2*dir[lca]);
		}
	}
	return 0;
}