Codevs 2370 小机房的树(LCA) 题解

题目来源:

http://codevs.cn/problem/2370/

题目描述:

 

题目描述 Description

小机房有棵焕狗种的树,树上有N个节点,节点标号为0到N-1,有两只虫子名叫飘狗和大吉狗,分居在两个不同的节点上。有一天,他们想爬到一个节点上去搞基,但是作为两只虫子,他们不想花费太多精力。已知从某个节点爬到其父亲节点要花费 c 的能量(从父亲节点爬到此节点也相同),他们想找出一条花费精力最短的路,以使得搞基的时候精力旺盛,他们找到你要你设计一个程序来找到这条路,要求你告诉他们最少需要花费多少精力

输入描述 Input Description

第一行一个n,接下来n-1行每一行有三个整数u,v, c 。表示节点 u 爬到节点 v 需要花费 c 的精力。
第n+1行有一个整数m表示有m次询问。接下来m行每一行有两个整数 u ,v 表示两只虫子所在的节点

输出描述 Output Description

一共有m行,每一行一个整数,表示对于该次询问所得出的最短距离。

样例输入 Sample Input

3

1 0 1

2 0 1

3

1 0

2 0

1 2

样例输出 Sample Output

1

1

2

数据范围及提示 Data Size & Hint

1<=n<=50000, 1<=m<=75000, 0<=c<=1000

解题思路:

      这题就是LCA的经典应用了,求树上两个点最短距离,和hdu 258很像。。。。

代码:

#include<iostream>
#include<cstring>
#define ll long long
using namespace std;
const int maxn=100005;
struct newt1{
	int to,next;ll val;
}edge[2*maxn];
struct newt2{
	int to,next,id;
}query[150005];
int n,m;
ll ans[maxn],dis[maxn];
int cnte,cntq,vis[maxn],father[maxn],heade[maxn],headq[maxn];
void init()
{
	for(int i=0;i<=n;i++)
		father[i]=i;
	memset(vis,0,sizeof(vis));
	memset(dis,0,sizeof(dis));
	memset(headq,-1,sizeof(headq));
	memset(heade,-1,sizeof(heade));
	memset(ans,0,sizeof(ans));
	cnte=cntq=0;
}
void addedge(int u,int v,ll w)
{
	edge[cnte].val=w;
	edge[cnte].to=v;
	edge[cnte].next=heade[u];
	heade[u]=cnte++;
}
void addquery(int u,int v,int id)
{
	query[cntq].id=id;
	query[cntq].to=v;
	query[cntq].next=headq[u];
	headq[u]=cntq++;
}
int fi(int x)
{
	if(x==father[x])return x;
	return father[x]=fi(father[x]);
}
void tarjan(int u)
{
	vis[u]=1;
	for(int i=heade[u];i!=-1;i=edge[i].next)
	{
		int v=edge[i].to;
		if(!vis[v]){
			dis[v]=dis[u]+edge[i].val;
			tarjan(v);
			father[v]=u;
		}
	}
	for(int i=headq[u];i!=-1;i=query[i].next)
	{
		int v=query[i].to;
		if(vis[v]){
			int z=fi(v);
			ans[query[i].id]=dis[u]-dis[z]-dis[z]+dis[v];
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	init();
	for(int i=1;i<=n-1;i++)
	{
		int a,b;ll c;
		cin>>a>>b>>c;
	    addedge(a,b,c);
		addedge(b,a,c);
	}
	cin>>m;
	for(int i=1;i<=m;i++)
	{
		int a,b;
		cin>>a>>b;
		addquery(a,b,i);
		addquery(b,a,i);
	}
	dis[0]=0;
	tarjan(0);
	for(int i=1;i<=m;i++)
	{
		cout<<ans[i]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/81198493