题意:一个城堡中有N个大厅,它们由N-1条长廊连成一个树状结构。在除了编号为1的大厅中的N-1个大厅里有一个宝物,宝物在这N-1个大厅中的概率相等。Gerald起始在1号大厅,他不知道宝物在哪个大厅。他要找出一条路径,使得他找到宝物所花时间的期望最小。
#include <stdio.h>
#include <memory.h>
#include <vector>
#include <algorithm>
using std::vector;
using std::sort;
const int N = 100005;
struct Graph {
int hed[N], pnt[N+N], val[N+N], nxt[N+N], cnt;
void init(int n) {
memset(hed + 1, -1, 4 * n);
cnt = 0;
}
void addedge(int x, int y, int v) {
pnt[cnt] = y; val[cnt] = v; nxt[cnt] = hed[x]; hed[x] = cnt++;
pnt[cnt] = x; val[cnt] = v; nxt[cnt] = hed[y]; hed[y] = cnt++;
}
} G;
int cnt[N];
long long cot[N], len[N];
bool cmp(const int &x, const int &y) {
return len[x] * cnt[y] < len[y] * cnt[x];
}
void dfs(int x, int f) {
cnt[x] = 1;
cot[x] = len[x] = 0;
vector<int> V;
for (int p = G.hed[x]; p != -1; p = G.nxt[p]) {
int y = G.pnt[p];
int w = G.val[p];
if (y == f) continue;
dfs(y, x);
V.push_back(y);
len[y] += w + w;
cot[y] += cnt[y] * w;
cnt[x] += cnt[y];
cot[x] += cot[y];
len[x] += len[y];
}
sort(V.begin(), V.end(), cmp);
int c = cnt[x] - 1;
for (int i = 0; i < V.size(); i++) {
c -= cnt[V[i]];
cot[x] += c * len[V[i]];
}
}
int main() {
int n, x, y, v, i;
scanf("%d", &n);
G.init(n);
for (i = 1; i < n; i++) {
scanf("%d %d %d", &x, &y, &v);
G.addedge(x, y, v);
}
dfs(1, -1);
printf("%.8lf\n", cot[1] / (n - 1.0));
return 0;
}