hdu6060[贪心+dfs] 2017多校3

/* hdu6060[贪心+dfs] 2017多校3*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int n, k, u, v, c;
struct Edge {
    LL cost;
    int to;
    Edge(int C = 0, int T = 0): cost(C), to(T) {}
};
vector<Edge> G[1000005];
int son[1000005];
LL ans = 0;
void dfs(int u, int fa) {
    son[u]++;
    for (int i = 0; i < (int)G[u].size(); i++) {
        Edge e = G[u][i];
        if (e.to == fa) continue;
        dfs(e.to, u);
        son[u] += son[e.to];
        ans += min(son[e.to], k) * e.cost;
    }
}
void init() {
    ans = 0;
    for (int i = 1; i <= n; i++) {
        G[i].clear();
    }
    memset(son, 0, sizeof(son));
}
void solve() {
    dfs(1, -1);
    printf("%lld\n", ans);
}
int main() {
    while (~scanf("%d%d", &n, &k)) {
        init();
        for (int i = 0; i < n - 1; i++) {
            scanf("%d%d%lld", &u, &v, &c);
            G[u].push_back(Edge(c, v));
            G[v].push_back(Edge(c, u));
        }
        solve();
    }
    return 0;
}

 

posted @ 2017-08-02 13:39  UnderSilence  阅读(153)  评论(0编辑  收藏  举报