1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <cstdio> #include <algorithm> using namespace std; typedef long long LL; const int N = 1e6 + 10, M = 2e6 + 10; int n; LL f[N], C[N], d[N], sz[N], wt[M]; int idx, hd[N], nxt[M], edg[M]; void dfs1(int x) { sz[x] = C[x]; for (int i = hd[x]; ~i; i = nxt[i]) if (!d[edg[i]] && edg[i] != 1) { d[edg[i]] = d[x] + wt[i]; dfs1(edg[i]); sz[x] += sz[edg[i]]; } } void dfs2(int x) { for (int i = hd[x]; ~i; i = nxt[i]) if (!f[edg[i]]) { f[edg[i]] = f[x] + wt[i] * (sz[1] - sz[edg[i]]) - wt[i] * sz[edg[i]]; dfs2(edg[i]); } } void add(int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1; i <= n; i++) scanf("%lld", &C[i]); for (int i = 1, a, b, c; i < n; i++) { scanf("%d%d%d", &a, &b, &c); add(a, b, c); add(b, a, c); } d[1] = 0; dfs1(1); for (int i = 1; i <= n; i++) f[1] += d[i] * C[i]; dfs2(1); LL mn = f[1]; for (int i = 2; i <= n; i++) mn = min(mn, f[i]); printf("%lld", mn); return 0; }
|