1 5 0 1 6 0 2 3 0 3 7 3 4 2
8.6
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int const MAX = 1e4 + 5; int n, cnt, head[MAX], num[MAX]; double sum; struct EDGE { int v, w, next; }e[2 * MAX]; void Add(int u, int v, int w) { e[cnt].v = v; e[cnt].w = w; e[cnt].next = head[u]; head[u] = cnt ++; } void DFS(int u, int fa) { num[u] = 1; for(int i = head[u]; i != -1; i = e[i].next) { int v = e[i].v; int w = e[i].w; if(v != fa) { DFS(v, u); num[u] += num[v]; sum += 1.0 * num[v] * (n - num[v]) * w; } } } int main() { int T; scanf("%d", &T); while(T --) { cnt = 0; sum = 0; memset(head, -1, sizeof(head)); scanf("%d", &n); for(int i = 0; i < n - 1; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); Add(u, v, w); Add(v, u, w); } DFS(0, -1); printf("%.7f\n", sum / (1.0 * n * (n - 1) / 2.0)); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 2376 Average distance (树形dp)
原文地址:http://blog.csdn.net/tc_to_top/article/details/47154041