【Average distance】【HDU - 2376 】(树形dp)

题目:

Given a tree, calculate the average distance between two vertices in the tree. For example, the average distance between two vertices in the following tree is (d 01 + d 02 + d 03 + d 04 + d 12 +d 13 +d 14 +d 23 +d 24 +d 34)/10 = (6+3+7+9+9+13+15+10+12+2)/10 = 8.6. 

 

Input

On the first line an integer t (1 <= t <= 100): the number of test cases. Then for each test case: 

One line with an integer n (2 <= n <= 10 000): the number of nodes in the tree. The nodes are numbered from 0 to n - 1. 

n - 1 lines, each with three integers a (0 <= a < n), b (0 <= b < n) and d (1 <= d <= 1 000). There is an edge between the nodes with numbers a and b of length d. The resulting graph will be a tree. 
 

Output

For each testcase: 

One line with the average distance between two vertices. This value should have either an absolute or a relative error of at most 10 -6 
 

Sample Input

1
5
0 1 6
0 2 3
0 3 7
3 4 2

Sample Output

8.6

解题报告:树形dp基础题目,首先题目要求就是求任意两点之间的距离之和的平均值。树形图是肯定的了,要求出每两个点之间的距离和不是很现实,所以咱们可以转化一下,来求解一条边到底被走了多少次,咱们将这些求和,最后除以总边数即可。

ac代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
const int maxn = 1e4+1000;
struct Edg{
	int v,next,len;
}e[maxn<<1];
int far[maxn],eid;
int size[maxn];
int n;
ll sum;
void add_edg(int a,int b,int le)
{
	e[++eid].len=le;
	e[eid].v=b;
	e[eid].next=far[a];
	far[a]=eid;
}
void dfs(int u,int f)
{
	size[u]=1;
	for(int i=far[u];i!=0;i=e[i].next)
	{
		int v=e[i].v;
		if(v==f)
		{
			continue;
		}
		dfs(v,u);
		size[u]+=size[v];
                   //累计结点数
		sum+=(ll)size[v]*(n-size[v])*e[i].len;//求这一条边走了多少次*它的长度。
	}
	return ;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		memset(far,0,sizeof(far));
		eid=0;
		for(int i=1;i<=n-1;i++)
		{
			int a,b,c;
			cin>>a>>b>>c;
			add_edg(a+1,b+1,c);
			add_edg(b+1,a+1,c);
		}
		sum=0;
		dfs(1,0);
		double p=n*(n-1)/2;
		printf("%.6lf\n",(double)sum/p);
	}
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值