From f5ab5fa54adb472de25d37aea63a8f0f6ab724aa Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sun, 29 Jan 2023 19:53:04 +0800 Subject: [PATCH] =?UTF-8?q?P4189=20[CTSC2010]=E6=98=9F=E9=99=85=E6=97=85?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/100786864 --- Luogu/P4189/P4189.cpp | 84 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Luogu/P4189/P4189.cpp diff --git a/Luogu/P4189/P4189.cpp b/Luogu/P4189/P4189.cpp new file mode 100644 index 00000000..94c15baf --- /dev/null +++ b/Luogu/P4189/P4189.cpp @@ -0,0 +1,84 @@ +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 50005; + +int n, h[N], son[N], ans[N], res; +std::vector g[N]; + +void dfs1(int u, int f) { + for (int v : g[u]) { + if (v == f) continue; + + dfs1(v, u); + + int x = std::min(h[u], h[v]); + + h[u] -= x, h[v] -= x; + res += x * 2; + + if (h[v]) son[u] = v; + } +} + +void dfs2(int u, int f) { + ans[u] = res; + + for (int v : g[u]) { + if (v == f) continue; + + if (h[u]) { + h[u]--, res++; + + dfs2(v, u); + + h[u]++, res--; + } else if (son[v]) { + h[son[v]]--, res++; + + dfs2(v, u); + + h[son[v]]++, res--; + } else { + h[v]++, res--; + + dfs2(v, u); + + h[v]--, res++; + } + } +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n; + + for (int i = 1; i <= n; i++) { + cin >> h[i]; + } + + for (int i = 1, x, y; i < n; i++) { + cin >> x >> y; + + h[++x]--, h[++y]--; + g[x].emplace_back(y); + g[y].emplace_back(x); + + res += 2; + } + + dfs1(1, 0); + dfs2(1, 0); + + for (int i = 1; i <= n; i++) { + cout << ans[i] << endl; + } + + return 0; +}