CodeForces 101D

题意:一个城堡中有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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值