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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <bits/stdc++.h> using namespace std; #define resetIO(x) \ freopen(#x ".in", "r", stdin), freopen(#x ".out", "w", stdout) #define debug(fmt, ...) \ fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) template <class _Tp> inline _Tp& read(_Tp& x) { bool sign = false; char ch = getchar(); double tmp = 1; for (; !isdigit(ch); ch = getchar()) sign |= (ch == '-'); for (x = 0; isdigit(ch); ch = getchar()) x = x * 10 + (ch ^ 48); return sign ? (x = -x) : x; } template <class _Tp> inline void write(_Tp x) { if (x < 0) putchar('-'), x = -x; if (x > 9) write(x / 10); putchar((x % 10) ^ 48); } bool m_be; using ll = long long; const int MAXN = 5e4 + 10; const int INF = 0x3f3f3f3f; int n, cnt[MAXN], deg[MAXN], ans[MAXN]; vector<int> g[MAXN]; void dfs1(int u, int f) { for (auto v : g[u]) { if (v == f) continue; dfs1(v, u); int t = min(cnt[u], cnt[v]); cnt[u] -= t, cnt[v] -= t, ans[1] += t + t; } } void dfs2(int u, int f) { if (cnt[f]) { --cnt[f], ans[u] = ans[f] + 1; for (auto v : g[u]) if (v != f) dfs2(v, u); ++cnt[f]; } else { int nxt = 0; for (auto v : g[u]) if (cnt[v]) nxt = 1; if (nxt) --cnt[nxt], ans[u] = ans[f] + 1; else ++cnt[u], ans[u] = ans[f] - 1; for (auto v : g[u]) if (v != f) dfs2(v, u); if (nxt) ++cnt[nxt]; else --cnt[u]; } } bool m_ed; signed main() { read(n); for (int i = 1; i <= n; ++i) read(cnt[i]); for (int i = 1; i < n; ++i) { int u, v; ++read(u), ++read(v); g[u].push_back(v), g[v].push_back(u); ++deg[u], ++deg[v]; } for (int i = 1; i <= n; ++i) cnt[i] -= deg[i], ans[1] += deg[i]; dfs1(1, 0); for (auto x : g[1]) dfs2(x, 1); for (int i = 1; i <= n; ++i) write(ans[i]), putchar('\n'); return 0; }
|