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.
|
|
|
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
const int N = 200010, M = N << 1;
|
|
|
|
|
|
|
|
// 链式前向星
|
|
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
|
|
void add(int a, int b, int c = 0) {
|
|
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
|
|
}
|
|
|
|
|
|
|
|
int n, c[N], f1[N], f2[N];
|
|
|
|
|
|
|
|
void dfs1(int u, int fa) {
|
|
|
|
if (c[u])
|
|
|
|
f1[u] = 1;
|
|
|
|
else
|
|
|
|
f1[u] = -1;
|
|
|
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
int v = e[i];
|
|
|
|
if (v == fa) continue;
|
|
|
|
dfs1(v, u);
|
|
|
|
f1[u] += max(f1[v], 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void dfs2(int u, int fa) {
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
int v = e[i];
|
|
|
|
if (v == fa) continue;
|
|
|
|
f2[v] = max(f2[u] + f1[u] - max(f1[v], 0), 0);
|
|
|
|
dfs2(v, u);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
int main() {
|
|
|
|
// 初始化链式前向星
|
|
|
|
memset(h, -1, sizeof h);
|
|
|
|
cin >> n;
|
|
|
|
|
|
|
|
for (int i = 1; i <= n; i++) cin >> c[i];
|
|
|
|
|
|
|
|
for (int i = 1; i <= n - 1; i++) {
|
|
|
|
int a, b;
|
|
|
|
cin >> a >> b;
|
|
|
|
add(a, b), add(b, a);
|
|
|
|
}
|
|
|
|
|
|
|
|
dfs1(1, 1);
|
|
|
|
|
|
|
|
dfs2(1, 1);
|
|
|
|
for (int i = 1; i <= n; i++) printf("%d ", f1[i] + f2[i]);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|