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.

56 lines
1.0 KiB

2 years ago
#include <bits/stdc++.h>
2 years ago
using namespace std;
2 years ago
using VI = vector<int>;
using VVI = vector<VI>;
VI a;
VI dp;
VI ans;
VVI e;
void dfs(int x, int fa = -1) {
dp[x] = a[x];
for (int to : e[x]) {
if (to == fa) continue;
dfs(to, x);
dp[x] += max(0, dp[to]);
2 years ago
}
}
2 years ago
void rdfs(int x, int fa = -1) {
ans[x] = dp[x];
for (int to : e[x]) {
if (to == fa) continue;
dp[x] -= max(0, dp[to]);
dp[to] += max(0, dp[x]);
rdfs(to, x);
dp[to] -= max(0, dp[x]);
dp[x] += max(0, dp[to]);
2 years ago
}
}
2 years ago
2 years ago
int main() {
2 years ago
int n;
2 years ago
cin >> n;
2 years ago
a = dp = ans = VI(n);
e = VVI(n);
2 years ago
2 years ago
for (int i = 0; i < n; ++i) {
cin >> a[i];
if (a[i] == 0) a[i] = -1;
2 years ago
}
2 years ago
for (int i = 0; i < n - 1; ++i) {
int x, y;
cin >> x >> y;
--x, --y;
e[x].push_back(y);
e[y].push_back(x);
2 years ago
}
2 years ago
dfs(0);
rdfs(0);
2 years ago
2 years ago
for (int ret : ans) cout << ret << " ";
cout << endl;
2 years ago
return 0;
2 years ago
}