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.

66 lines
1.3 KiB

2 years ago
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
2 years ago
using namespace std;
2 years ago
const int N = 2e5 + 10;
2 years ago
2 years ago
struct Edge {
int to, next;
} edge[N << 1];
int idx;
int h[N];
2 years ago
2 years ago
void add_edge(int u, int v) {
edge[++idx] = {v, h[u]};
h[u] = idx;
}
2 years ago
2 years ago
int dp[N], f[N], vis[N], w[N];
int n;
2 years ago
2 years ago
void dfs1(int p, int fa) {
dp[p] = w[p];
for (int i = h[p]; ~i; i = edge[i].next) {
int to = edge[i].to;
if (to == fa) continue;
dfs1(to, p);
if (dp[to] > 0) {
vis[to] = 1;
dp[p] += dp[to];
}
2 years ago
}
}
2 years ago
void dfs2(int p, int fa) {
for (int i = h[p]; ~i; i = edge[i].next) {
int to = edge[i].to;
if (to == fa) continue;
int val = f[p] - (vis[to] ? dp[to] : 0);
f[to] = dp[to] + (val > 0 ? val : 0);
dfs2(to, p);
2 years ago
}
}
2 years ago
2 years ago
int main() {
2 years ago
memset(h, -1, sizeof h);
2 years ago
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
w[i] = (x ? x : -1);
}
for (int i = 1; i <= n - 1; i++) {
int u, v;
scanf("%d%d", &u, &v);
add_edge(u, v);
add_edge(v, u);
2 years ago
}
2 years ago
2 years ago
dfs1(1, 0);
2 years ago
f[1] = dp[1];
2 years ago
dfs2(1, 0);
2 years ago
for (int i = 1; i <= n; i++) printf("%d ", f[i]);
2 years ago
return 0;
2 years ago
}