学到了一种 建树 方法,比 之前光靠 father[] 来建树更加 可靠,因为这个可以双向。dfs (i,j) i节点 便是根节点,可以换不同的根节点,但是答案输出的时候也要是相应的根节点进行输出,这个也可以理解。
初学的时候,可以在dfs函数中,在dfs上下,输出father,root,son 这三个值,可以便于理解
题目:
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 (d01 + d02+ d03 + d04 + d12 +d13 +d14 +d23 +d24 +d34)/10 = (6+3+7+9+9+13+15+10+12+2)/10 = 8.6.
题意:任意两点的距离和的平均数
思路:建树,数son节点的两边 点的个数,两边点的个数相乘 就是 该边总共要用到几次
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=10005;
double dp[maxn];
int head[maxn<<1],top,n;//head[i] 边i 的起始
int sum[maxn];
struct Edge{
int to,from;
int w;
}edge[maxn<<1];
void into(){
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
memset(sum,0,sizeof(sum));
top=0;
}
void add(int u,int v,int w){
edge[top].to=v;
edge[top].w=w;
edge[top].from=head[u];
head[u]= top++;
}
void dfs(int root,int father){
//father -> root -> son
sum[root]=1;
for(int i=head[root];i!=-1;i=edge[i].from){
int son=edge[i].to;
int len=edge[i].w;
if(son==father)
continue;
dfs(son,root);
sum[root] +=sum[son];// 累计节点数
// 要重复走,sum[son]*(n-sum[son])次,len边
dp[root] +=dp[son]+(sum[son]*(n-sum[son]))*(double)len;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
into();
scanf("%d",&n);
int u,v,w;
for(int i=1;i<n;i++){
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);add(v,u,w);
}
dfs(0,-1);
int s=(n*(n-1))/2;
printf("%.10lf\n",(double)dp[0]/s);
}
return 0;
}