You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
939 B
41 lines
939 B
2 years ago
|
#include <bits/stdc++.h>
|
||
|
using namespace std;
|
||
|
#define LL long long
|
||
|
const int N = 1e5 + 10;
|
||
|
vector<int> g[N];
|
||
|
int a[N];
|
||
|
int dp[N], siz[N];
|
||
|
int ans = 1e9;
|
||
|
void dfs1(int u, int fa, int dep) {
|
||
|
siz[u] = a[u];
|
||
|
for (auto v : g[u]) {
|
||
|
if (v == fa) continue;
|
||
|
dfs1(v, u, dep + 1);
|
||
|
siz[u] += siz[v];
|
||
|
}
|
||
|
dp[1] += dep * a[u]; // 先算出1点的总代价
|
||
|
}
|
||
|
void dfs2(int u, int fa) {
|
||
|
for (auto v : g[u]) {
|
||
|
if (v == fa) continue;
|
||
|
dp[v] = dp[u] + siz[1] - siz[v] * 2;
|
||
|
dfs2(v, u);
|
||
|
}
|
||
|
ans = min(ans, dp[u]);
|
||
|
}
|
||
|
int main() {
|
||
|
int n;
|
||
|
cin >> n;
|
||
|
for (int i = 1; i <= n; i++) {
|
||
|
cin >> a[i];
|
||
|
int u, v;
|
||
|
cin >> u >> v;
|
||
|
if (u > 0) g[i].push_back(u), g[u].push_back(i);
|
||
|
if (v > 0) g[i].push_back(v), g[v].push_back(i);
|
||
|
}
|
||
|
dfs1(1, 0, 0);
|
||
|
dfs2(1, 0); // 换根
|
||
|
cout << ans;
|
||
|
return 0;
|
||
|
}
|