Code:
#include <bits/stdc++.h> #define setIO(s) freopen(s".in","r",stdin) #define maxn 1000000 #define inf 100000000000000 #define ll long long using namespace std; ll f[maxn], siz[maxn], sumv[maxn]; int C[maxn], hd[maxn], to[maxn << 1], nex[maxn << 1], val[maxn << 1]; int n, edges, root; ll tot; void add(int u, int v, int c) { nex[++edges] = hd[u], hd[u] = edges, to[edges] = v, val[edges] = c; } void dfs(int u, int ff) { siz[u] = C[u], f[u] = 0; for(int i = hd[u]; i ; i = nex[i]) { int v = to[i]; if(v == ff) continue; dfs(v, u); siz[u] += siz[v]; f[u] = max(f[u], siz[v]); } f[u] = max(f[u], tot - siz[u]); if(f[u] < f[root]) root = u; } void calc(int u,int ff) { siz[u] = C[u], sumv[u] = 0; for(int i = hd[u]; i ; i = nex[i]) { int v = to[i]; if(v == ff) continue; calc(v, u); siz[u] += siz[v]; sumv[u] += sumv[v] + val[i] * siz[v]; } } int main() { // setIO("input"); scanf("%d",&n); for(int i = 1; i <= n; ++i) scanf("%d",&C[i]), tot += C[i]; for(int i = 1, u, v, c; i < n; ++i) { scanf("%d%d%d",&u,&v,&c); add(u, v, c); add(v, u, c); } f[0] = inf, root = 0, dfs(1, 0); memset(siz, 0, sizeof(siz)), calc(root, 0); printf("%lld\n",sumv[root]); return 0; }
BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会 树形DP_带权重心
原文:https://www.cnblogs.com/guangheli/p/10982700.html