poj 1986 Distance Queries LCA

Distance Queries

Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 12716 Accepted: 4501
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.

题目解析:

这个题就是给你一棵树,然后问你树上两点的最小距离。网上有题解说要判断一下是否联通,然而我没有判断也AC了。也有其他人用的TarjanAC了。
注意:本题数据比较强,所以要用倍增,同时题目给的点的位置不一定,编号小的点可能会在下面,所以倍增更新时要在dfs里更新。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int SK = 100000;
int first[SK], next[SK], tot = 0;
int sd[SK], t[SK][30], fa[SK], val[SK];
bool use[SK];
struct qer
{
	int from, to, cost;
}es[SK];
void init()
{
	memset(first, -1, sizeof(first));
	tot = 0;
}
void build(int f, int t, int d)
{
	es[++tot] = (qer){f, t, d};
	next[tot] = first[f];
	first[f] = tot;
}
void dfs(int x)
{
	use[x] = 1;
	int v;
	for(int i = first[x];i != -1;i = next[i])
	{
		v = es[i].to;
		if(!sd[v] && use[v] == 0)
		{
			t[v][0]=x;
			for(int j=1;j<=20;j++)
				t[v][j]=t[t[v][j-1]][j-1];
			use[v] = 1;
			val[v]= val[x] + es[i].cost;
			sd[v] = sd[x] + 1;
			fa[v] = x;
			dfs(v);
		}
	}
}
int lca(int a, int b)
{
	if(sd[a] < sd[b])
		swap(a, b);
	int tt = sd[a] - sd[b];
	for(int i = 0;i <= 20;i ++)
	{
		if((1<<i)&tt)
			a = t[a][i];
	}
	for(int i = 20;i >= 0;i --)
	{
		if(t[a][i] != t[b][i])
		{
			a = t[a][i];
			b = t[b][i];
		}
	}
	if(a!= b)
		return fa[a];
	return a;
}
int main()
{
	init();
	int n, m;
	cin>>n>>m;
	for(int i = 1;i <= m;i ++)
	{
		int u, v, c;
		char a;
		scanf("%d%d%d", &u, &v, &c);
		a = getchar();
		while(a < 'A' || a > 'Z')
			a = getchar();
		build(u, v, c);
		build(v, u, c);
	}
	val[0] = 0;
	dfs(1);
	int q;
	scanf("%d", &q);
	for(int i = 1;i <= q;i ++)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		if(sd[u] < sd[v])
			swap(u, v);
		int ans = lca(u, v);
		if(ans == u)
			printf("%d\n",val[v]-val[u]);
		else
		{
			printf("%d\n",val[u]+val[v]-2*val[ans]);
		}
	}
	return 0;
}

 

上一篇
下一篇