HDU 2376 Average distance(树上两点间的期望)

本文介绍了一种计算树状结构中任意两点间平均距离的方法。通过递归深度优先搜索算法,遍历每个节点并计算其子树大小及贡献值,最终得出整棵树的平均距离。

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

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=20005;
struct node
{
    int x,y;
    int v,next;
}edge[maxn];
int head[maxn],cnt,n;
int sz[maxn];
double an;
int add(int x,int y,int v)
{
    edge[cnt].x=x;
    edge[cnt].y=y;
    edge[cnt].v=v;
    edge[cnt].next=head[x];
    head[x]=cnt++;
}
int dfs(int root,int fa)
{
    sz[root]=1;
    for(int i=head[root];i!=-1;i=edge[i].next)
    {
        int a=edge[i].y;
        int b=edge[i].v;
        if(a==fa)   continue;
        dfs(a,root);
        sz[root]=sz[root]+sz[a];
        an=an+(double)(n-sz[a])*sz[a]*b;
    }
}
int main()
{
    int t;  scanf("%d",&t);
    while(t--)
    {
        memset(head,-1,sizeof(head));
        memset(sz,0,sizeof(sz));
        cnt=0;
        scanf("%d",&n);
        for(int i=0;i<n-1;i++)
        {
            int x,y,z;  scanf("%d%d%d",&x,&y,&z);
            add(x,y,z); add(y,x,z);
        }
        an=0.0;
        dfs(0,-1);
        printf("%.7f\n",an/ (1.0 * n * (n - 1) / 2.0));
    }
}

Average distance

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 943    Accepted Submission(s): 318
Special Judge


Problem Description
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
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   2378  2379  2377  2380  2381 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值