解题思路
题目都很明显告诉你这是一棵树了,那你就老老实实的建个树跑每条路的花费就行了。
先找到每条路的人流量,再计算一次的花费,这些人还要原路返回一次,最终输出乘一个二就行了
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 2e5 + 7; struct Node { int dst, val, id; }; vector<Node> arr[MAXN]; ll num[MAXN], a[MAXN], sum[MAXN], res[MAXN]; int n; ll x; void dfs(int now, int fa) { num[now] = 1; sum[now] = a[now]; for (int i = 0; i < arr[now].size(); ++i) { int dst = arr[now][i].dst; int w = arr[now][i].val; if (dst == fa) continue; dfs(dst, now); num[now] += num[dst]; sum[now] += sum[dst]; res[arr[now][i].id] += w * ((n - num[dst]) * sum[dst] + num[dst] * (x - sum[dst])); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%lld", a + i); x += a[i]; } for (int i = 0; i < n - 1; ++i) { int u, v, z; scanf("%d %d %d", &u, &v, &z); Node temp; temp.id = i; temp.dst = v; temp.val = z; arr[u].push_back(temp); temp.dst = u; arr[v].push_back(temp); } dfs(1, 0); for (int i = 0; i < n - 1; ++i) printf("%lld\n", res[i] << 1); return 0; }