题目:
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);
}
}