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.
题解:LCA离线算法,从叶子节点开始向上找,并且不断更新父节点,不同分支上的点的最近祖先肯定是另外一点的父节点,同一分支上的也是,不过此时另外一点的父节点就是自身。画个图按着推上去就知道了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int INF = 10005;
struct Node
{
int pos;
int dis;
};
bool visited[INF];
int d[10005]; //保存到根节点的距离
vector<Node> vec[INF]; //保存邻接点与距离
vector<int> q[INF]; //保存询问
int ans[INF]; //保存结果
int fa[INF]; //父节点
int p1[INF]; //询问的第一个点 下表为访问顺序
int p2[INF]; //询问的第二个点,
int find(int x) //并查集
{
if(x == fa[x])
{
return x;
}
return fa[x] = find(fa[x]);
}
void dfs(int x,int pre,int dis)
{
visited[x] = true;
fa[x] = x;
d[x] = dis; //该点到根的距离
for(int i = 0;i < vec[x].size();i++)
{
int k = vec[x][i].pos;
if(!visited[k])
{
dfs(k,x,dis + vec[x][i].dis);
}
}
for(int i = 0;i < q[x].size();i++) //访问中出现该点判断另外一点是否访问
{
int k = (x == p1[q[x][i]] ? p2[q[x][i]] : p1[q[x][i]]); //另外一点的祖先就是最近祖先
if(-1 == fa[k]) //另外一点未访问
{
continue;
}
ans[q[x][i]] = d[x] + d[k] - 2 * d[find(k)]; //距离=x到根的距离+k到根的距离-2*最近祖先
}
fa[x] = find(pre); //该点的祖先更新为父节点祖先
}
int main()
{
int n,m;
cin>>n>>m;
int a,b,c;
char d;
Node t1,t2;
for(int i = 0;i < m;i++)
{
scanf("%d %d %d %c",&a,&b,&c,&d);
t1.pos = a;
t1.dis = c;
t2.pos = b;
t2.dis = c;
vec[t1.pos].push_back(t2);
vec[t2.pos].push_back(t1);
}
int query;
cin>>query;
for(int i = 0;i < query;i++)
{
scanf("%d%d",&p1[i],&p2[i]);
q[p1[i]].push_back(i); //以后通过q可以得到访问的另外一点
q[p2[i]].push_back(i);
}
memset(fa,-1,sizeof(fa));
memset(visited,false,sizeof(visited));
dfs(1,1,0); //把1当作根节点,祖先就是自身,到自己的距离为0
for(int i = 0;i < query;i++)
{
printf("%d\n",ans[i]);
}
for(int i = 0;i < INF;i++) //千万不要忘记
{
vec[i].clear();
q[i].clear();
}
return 0;
}