您的位置:首页 > 其它

LCA在线算法(hdu2586)

2014-04-09 15:01 148 查看
hdu2586


How far away ?

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4183 Accepted Submission(s): 1598



Problem Description

There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always
unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.

Input

First line is a single integer T(T<=10), indicating the number of test cases.

For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road
connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.

Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.

Output

For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.

Sample Input

2
3 2
1 2 10
3 1 15
1 2
2 3

2 2
1 2 100
1 2
2 1


Sample Output

10
25
100
100


分析:

LCA最近公共祖先其实就是利用树形结构求两点间的最短路;一般题目说有n个点,且仅有n-1条边,则优先考虑LCA算法(离线或在线)

程序:

#include"stdio.h"
#include"string.h"
#include"stdlib.h"
#define M 40009
#include"string"
#include"map"
#include"iostream"
using namespace std;
struct st
{
int u,v,next,w;
}edge[M];
int head[M],f[M],rank[M],use[M],dis[M],t;
void init()
{
t=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int w)
{
edge[t].u=u;
edge[t].v=v;
edge[t].w=w;
edge[t].next=head[u];
head[u]=t++;
}
void dfs(int u)
{
int i;
use[u]=1;
for(i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(!use[v])
{
rank[v]=rank[u]+1;
dis[v]=dis[u]+edge[i].w;
dfs(v);
}
}
}
int LCA(int u,int v)
{
if(u==v)
return u;
else if(rank[u]>rank[v])
return LCA(f[u],v);
else
return LCA(u,f[v]);
}
int main()
{
int T,i,a,b,c,m,n;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
f[i]=i;
init();
for(i=1;i<n;i++)
{
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
f[b]=a;
}
memset(dis,0,sizeof(dis));
memset(rank,0,sizeof(rank));
memset(use,0,sizeof(use));
for(i=1;i<=n;i++)
if(f[i]==i)
dfs(i);
while(m--)
{
scanf("%d%d",&a,&b);
int ans=LCA(a,b);
printf("%d\n",dis[a]+dis[b]-2*dis[ans]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: