USACO 2004 February Green Distance Queries

题目描述

Farmer John's cows refused to run in his marathon since he chose apath much too long for their leisurely lifestyle. He therefore wants to find apath of a more reasonable length. The input to this problem consists of thesame input as in "Navigation Nightmare",followed by a line containinga single integer K, followed by K "distance queries". Each distancequery is a line of input containing two integers, giving the numbers of twofarms between which FJ is interested in computing distance (measured in thelength of the roads along the path between the two farms). Please answer FJ'sdistance queries as quickly as possible!

 输入

* 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: Eachline corresponds to a distance query and contains the indices of two farms.

 输出

* Lines 1..K: For each distance query, output on a single line aninteger giving the appropriate distance.

 样例输入

76

1 613 E

6 3 9E

3 5 7S

4 1 3N

2 420 W

4 7 2S

3

1 6

1 4

2 6

样例输出

13

3

36

题解:标准LCA模板题,输入数据可忽略道路的方向。

#include <cstdio>
#include <cmath>
#define N 40005
int n,m,k,first[N*2],next[N*2],v[N*2],w[N*2];
int x,y,z,cnt,dep[N],f[N][20],dis[N];
bool vis[N];
using namespace std;
inline void dfs(int x,int k)
{
    dep[x]=k;
    vis[x]=1;
    for (int i=first[x];i;i=next[i])
    if (!vis[v[i]])
    {
    	f[v[i]][0]=x;
    	dis[v[i]]=dis[x]+w[i];
    	dfs(v[i],k+1);
    }		
}
inline int find(int x,int y)
{
	if (dep[x]<dep[y])
	{
		int t=x;x=y;y=t;
	}
	for (int i=log2(n);i>=0;i--)
	  if (dep[f[x][i]]>=dep[y]) x=f[x][i];
	if (x==y) return x;
	for (int i=log2(n);i>=0;i--)
	  if (f[x][i]!=f[y][i])
	  {
	  	x=f[x][i];
	  	y=f[y][i];
	  } 
	return f[x][0];
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=m;i++)
	{
		char ch[2];
		scanf("%d%d%d %c",&x,&y,&z,&ch);
		next[++cnt]=first[x];
		first[x]=cnt;
		v[cnt]=y;
		w[cnt]=z;
		next[++cnt]=first[y];
		first[y]=cnt;
		v[cnt]=x;
		w[cnt]=z;
	}
	dfs(1,1);
	for (int j=1;j<=log2(n);j++)
	   for (int i=1;i<=n;i++)
	     f[i][j]=f[f[i][j-1]][j-1];
	scanf("%d",&k); 
	for (int i=1;i<=k;i++) 
	{
		scanf("%d%d",&x,&y);
		z=find(x,y);
		printf("%d\n",dis[x]+dis[y]-dis[z]*2);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhouhongkai06/article/details/80471911
今日推荐