hdu 2376 Average distance DFS 求树上任意两点距离和
题意:标题都已经说明了题意了。求树上任意两点距离和的平均值。
分析:分析过程和
《 hdu 5723 Abandoned country 最小生成树+DFS》中求树上任意两点距离之和是完全一样的。思路就是先求出每条边两端的点的个数,然后对于每条边,假如该边两端的点的个数为A,B,那么这条边对总共的距离和的贡献值就是A*B*这条边的权值,然后将所有的边的贡献值累加就行了。
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
#define fst first
#define snd second
typedef __int64 LL;
//typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int MAXN = 10000 + 5;
// const int MAXM = 1000000 + 5;
struct TNode {
int v, w;
TNode() {}
TNode(int v, int w) : v(v), w(w) {}
};
int T, N;
vector<TNode> G[MAXN];
int sum[MAXN];
LL ans;
void init() {
memset(sum, 0, sizeof(sum));
for (int i = 0; i < N; i++) G[i].clear();
}
void dfs(int root, int father) {
sum[root] = 1;
for (int i = 0; i < G[root].size(); i++) {
TNode& e = G[root][i];
int son = e.v;
if (son == father) continue;
dfs(son, root);
sum[root] += sum[son];
ans += (LL)(sum[son] * (N - sum[son])) * e.w;
}
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
scanf("%d", &T);
while (T --) {
init();
scanf("%d", &N);
int u, v, w;
for (int i = 0; i < N - 1; i++) {
scanf("%d %d %d", &u, &v, &w);
G[u].push_back(TNode(v, w));
G[v].push_back(TNode(u, w));
}
ans = 0;
dfs(0, -1);
int s = N * (N - 1) / 2;
printf("%.6lf\n", (double) ans / s);
}
return 0;
}