题目链接:http://poj.org/problem?id=1986
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!
题目描述:已知n(n<=40000)个农场和一些农场之间的距离,给出很多组询问,在线询问每两个农场之间的距离。
算法分析:这道题运用LCA的在线和离线算法都可以。
离线LCA思路:以某一个农场为树根,用数组保存剩余每个农场到树根的距离为dist[u],那么农场u和v的距离=dist[u]+dist[v]-2*dist[q](q为LCA(u,v))。
我的做法虽然可以AC,但是很慢,有很大的优化空间:在两个节点不断向树根靠近的同时,把每向上走一层的路径上的权值(即农场之间的距离)加起来即为答案。我用离线的LCA代码运用在在线方法上,仔细想想在求每个节点的深度时就可以把离线思想中dist数组求出来了,更简单,速度更快。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>
#define inf 0x7fffffff
using namespace std;
const int maxn=+;
const int max_log_maxn=; int n,m,root;
vector<pair<int,int> > G[maxn];
int father[max_log_maxn][maxn],d[maxn];
int sum[max_log_maxn][maxn]; void dfs(int u,int p,int depth)
{
father[][u]=p;
d[u]=depth;
int num=G[u].size();
for (int i= ;i<num ;i++)
{
int v=G[u][i].first;
int len=G[u][i].second;
if (v != p)
{
sum[][v]=len;
dfs(v,u,depth+);
}
}
} void init()
{
dfs(root,-,);
for (int k= ;k+<max_log_maxn ;k++)
{
for (int i= ;i<=n ;i++)
{
if (father[k][i]<)
{
father[k+][i]=-;
sum[k+][i]=;
}
else
{
father[k+][i]=father[k][father[k][i] ];
sum[k+][i]=sum[k][i]+sum[k][father[k][i] ];
}
}
}
} int LCA(int u,int v)
{
if (d[u]>d[v]) swap(u,v);
int Sum=;
for (int k= ;k<max_log_maxn ;k++)
{
if ((d[v]-d[u])>>k & )
{
Sum += sum[k][v];
v=father[k][v];
}
}
if (u==v) return Sum;
for (int k=max_log_maxn- ;k>= ;k--)
{
if (father[k][u] != father[k][v])
{
Sum += sum[k][u];
Sum += sum[k][v];
u=father[k][u];
v=father[k][v];
}
}
Sum += sum[][u];
Sum += sum[][v];
return Sum;
} int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
int u,v,length;
char ch[];
for (int i= ;i<=n ;i++) G[i].clear();
for (int i= ;i<max_log_maxn ;i++)
{
for (int j= ;j<maxn ;j++)
sum[i][j]=;
}
for (int i= ;i<m ;i++)
{
scanf("%d%d%d%s",&u,&v,&length,ch);
G[u].push_back(make_pair(v,length));
G[v].push_back(make_pair(u,length));
}
root=;
init();
int k;
scanf("%d",&k);
for (int i= ;i<k ;i++)
{
scanf("%d%d",&u,&v);
printf("%d\n",LCA(u,v));
}
}
return ;
}