1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include <bits/stdc++.h> using namespace std; const int N = 2e5 + 1, M = 2 * N; int n, u, v; int a[N], h[N], e[M], ne[M], idx; int dp[N]; void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 1; i < n; ++i) { scanf("%d%d", &u, &v); add(u, v), add(v, u); } function<void(int, int)> dfs = [&](int u, int f) { dp[u] = a[u] ? 1 : -1; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { dfs(v, u); if (dp[v] > 0) dp[u] += dp[v]; } } }; dfs(1, 0); function<void(int, int)> reroot = [&](int u, int f) { for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { int from = dp[u], to = dp[v]; if (to > 0) from -= to; if (from > 0) to += from; dp[v] = to; reroot(v, u); } } }; reroot(1, 0); for (int i = 1; i < n; ++i) printf("%d ", dp[i]); printf("%d\n", dp[n]); return 0; }
|