HDU 3534 Tree(树的直径)

本文介绍了一种高效算法,用于解决树结构中寻找最长路径及其数量的问题,即求解树的直径和圆点。通过深度优先搜索(DFS)和树型动态规划(Tree DP),文章详细阐述了如何在给定的树形结构中,找到距离最远的两个节点之间的路径长度及具有该最大距离的所有节点对的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

In the Data structure class of HEU, the teacher asks one problem: How to find the longest path of one tree and the number of such longest path?

Input

There are several test cases. The first line of each case contains only one integer N, means there are N nodes in the tree. N-1 lines follow, each line has three integers w,v and len, indicate that there is one edge between node w and v., and the length of the edge is len.
 

 

Output

For each test case, output the length of longest path and its number in one line.

 

Sample Input

4

1 2 100

2 3 50

2 4 50

4

1 2 100

2 3 50

3 4 50

Sample Output

150 2

200 1

给出一颗n个节点的树,每条边对应一个长度,求出距离最大的两个节点之间长度,并找出一共有多少个顶点对。

就是求树的直径和圆点,DFS可做,树型DP也可做。

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int INF=0x3f3f3f3f;
const int N=500000;
int head[N],num,Len[N],ans,node[N],k;
struct edge
{
	int ed,w,next;
}e[N*2];
void addedge(int x,int y,int w)
{
	e[num].ed=y;e[num].w=w;e[num].next=head[x];head[x]=num++;
	e[num].ed=x;e[num].w=w;e[num].next=head[y];head[y]=num++;
}
void dfs(int u,int fa)
{
	int i,v,temp;
	Len[u]=0;//最长边
	node[u]=1;//最长边的个数
	for(i=head[u];i!=-1;i=e[i].next)
	{
		v=e[i].ed;
		if(v==fa)continue;
		dfs(v,u);
		temp=Len[v]+e[i].w;
		if(temp+Len[u]>ans)//最长边经过v
		{
			k=node[v]*node[u];
			ans=temp+Len[u];
		}
		else if(temp+Len[u]==ans)
			k+=node[v]*node[u];
		if(Len[u]<temp)//更新最长边
		{
			Len[u]=temp;
			node[u]=node[v];
		}
		else if(Len[u]==temp)//更新最长边的个数
			node[u]+=node[v];
	}
}
int main()
{
	int n,i,x,y,w;
	while(scanf("%d",&n)!=-1)
	{
		memset(head,-1,sizeof(head));
		num=0;
		for(i=1;i<n;i++)
		{
			scanf("%d%d%d",&x,&y,&w);
			addedge(x,y,w);
		}
		ans=-INF;
		k=0;
		dfs(1,0);
		printf("%d %d\n",ans,k);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值