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 = 2e5 + 10, 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 f1[N];
|
|
|
|
int f2[N];
|
|
|
|
int vis[N];
|
|
|
|
int c[N]; // 颜色
|
|
|
|
int n; // 节点数量
|
|
|
|
|
|
|
|
void dfs1(int u, int fa) {
|
|
|
|
f1[u] = c[u];
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
int v = e[i];
|
|
|
|
if (v == fa) continue;
|
|
|
|
dfs1(v, u);
|
|
|
|
if (f1[v] > 0) {
|
|
|
|
vis[v] = 1;
|
|
|
|
f1[u] += f1[v];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void dfs2(int u, int fa) {
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
int v = e[i];
|
|
|
|
if (v == fa) continue;
|
|
|
|
int val = f2[u] - (vis[v] ? f1[v] : 0);
|
|
|
|
f2[v] = f1[v] + (val > 0 ? val : 0);
|
|
|
|
dfs2(v, u);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
// 初始化链式前向星
|
|
|
|
memset(h, -1, sizeof h);
|
|
|
|
cin >> n;
|
|
|
|
|
|
|
|
for (int i = 1; i <= n; i++) {
|
|
|
|
int x;
|
|
|
|
cin >> x;
|
|
|
|
c[i] = (x ? x : -1);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
int a, b;
|
|
|
|
cin >> a >> b;
|
|
|
|
add(a, b), add(b, a);
|
|
|
|
}
|
|
|
|
|
|
|
|
dfs1(1, 0);
|
|
|
|
f2[1] = f1[1];
|
|
|
|
dfs2(1, 0);
|
|
|
|
|
|
|
|
for (int i = 1; i <= n; i++) printf("%d ", f2[i]);
|
|
|
|
return 0;
|
|
|
|
}
|