版权声明:转载请注明出处 https://blog.csdn.net/qq_41593522/article/details/83993807
题意
问树上路径长度的期望值
题解
dfs求出每条边左右连接的点数,统计答案,最后*2/n/(n+1)
调试记录
无
#include <cstdio>
#include <cstring>
#define int long long
const int maxn = 1e4 + 5;
using namespace std;
struct node{
int to, next, l;
}e[maxn << 1];
int head[maxn], tot;
void addedge(int u, int v, int l){
e[++tot].to = v, e[tot].next = head[u], e[tot].l = l;
head[u] = tot;
}
long long ans; int size[maxn], n;
void dfs(int cur, int fa){
size[cur] = 1;
for (int i = head[cur]; i; i = e[i].next){
if (e[i].to != fa){
dfs(e[i].to, cur);
size[cur] += size[e[i].to];
ans += e[i].l * size[e[i].to] * (n - size[e[i].to]);
}
}
}
int T;
signed main(){
scanf("%lld", &T);
while (T--){
scanf("%lld", &n);
memset(e, 0, sizeof e);
memset(head, 0, sizeof head);
memset(size, 0, sizeof size);
tot = 0; ans = 0;
for (int u, v, l, i = 1; i < n; i++){
scanf("%lld%lld%lld", &u, &v, &l); u++, v++;
addedge(u, v, l), addedge(v, u, l);
}
dfs(1, 0);
printf("%.6lf\n", 2.0 * ans / n / (n - 1));
}
return 0;
}