inlinevoidadd(int u, int v, int w){ e[++tot].to = v; e[tot].w = w; e[tot].nxt = hd[u]; hd[u] = tot; }
ll f[N], sum[N];
voiddfs(int u, int fa){ sum[u] = c[u]; for (int i = hd[u], v; i; i = e[i].nxt) if ((v = e[i].to) != fa) { dfs(v, u); sum[u] += sum[v]; f[u] += f[v] + sum[v] * e[i].w; } }
ll ans[N];
voiddfs1(int u, int fa){ for (int i = hd[u], v; i; i = e[i].nxt) if ((v = e[i].to) != fa) { ans[v] = ans[u] - sum[v] * e[i].w + (sum[1] - sum[v]) * e[i].w; dfs1(v, u); } }
intmain(){ int n = rd(); for (int i = 1; i <= n; ++i) c[i] = rd(); for (int i = 1; i < n; ++i) { int u = rd(), v = rd(), w = rd(); add(u, v, w); add(v, u, w); } dfs(1, 1); ans[1] = f[1]; dfs1(1, 1); ll res = 1e18; for (int i = 1; i <= n; ++i) res = min(res, ans[i]); printf("%lld\n", res); return0; }
Post title:树形DP
Post author:Eva.Q
Create time:2022-07-01 12:30:55
Post link:https://qyy/2022/07/01/Algorithm/dp-on-tree/
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.