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!
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
题目大意:给出n个点和n-1条边的信息,对每个循环u、v输出从u到v的路径距离。
思路:那个方向没啥用,LCA模板题。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int maxn=4e4+5;
struct edge
{
int to,nxt;
ll dis;
};
edge Edge[maxn<<1];
int head[maxn];
int fa[maxn];//父节点
int deep[maxn];//深度
ll dist[maxn];
int n,m,cnt=0;
int f[maxn][30];
inline void addedge(int u,int v,ll dis)
{
Edge[++cnt].to=v,Edge[cnt].nxt=head[u],Edge[cnt].dis=dis,head[u]=cnt;
Edge[++cnt].to=u,Edge[cnt].nxt=head[v],Edge[cnt].dis=dis,head[v]=cnt;
}
void dfs(int u,int father)
{
deep[u]=deep[father]+1;
f[u][0]=father;
for(int i=1;i<=20;i++)
f[u][i]=f[f[u][i-1]][i-1];
for(int i=head[u];i;i=Edge[i].nxt)
{
if(Edge[i].to!=father)
{
dist[Edge[i].to]=dist[u]+Edge[i].dis;
dfs(Edge[i].to,u);
}
}
}
inline int skip(int x,int level)
{
for(int i=20;i>=0;i--)
if((1<<i)&level)
x=f[x][i];
return x;
}
inline int LCA(int u,int v)
{
if(deep[u]<deep[v])
swap(u,v);
u=skip(u,deep[u]-deep[v]);
if(u==v)
return u;
for(int i=20;i>=0;i--)
if(f[u][i]!=f[v][i])
u=f[u][i],v=f[v][i];
return f[u][0];
}
int main()
{
int u,v,grand;
char ch;
ll dis;
while(~scanf("%d%d",&n,&m))
{
cnt=0;
memset(head,0,sizeof(head));
for(int i=1;i<n;i++)
{
scanf("%d %d %lld %c",&u,&v,&dis,&ch);
addedge(u,v,dis);
}
dfs(1,0);
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
grand=LCA(u,v);
printf("%lld\n",dist[u]+dist[v]-2*dist[grand]);
}
}
return 0;
}