From 236c96d157f9a8a19d0e28f69d28238abf50c546 Mon Sep 17 00:00:00 2001 From: Thalisson-Alves Date: Tue, 3 Sep 2024 21:58:25 -0300 Subject: [PATCH] graph, tree, small to large --- submissions/CodeForces/600/e.cpp | 79 ++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 submissions/CodeForces/600/e.cpp diff --git a/submissions/CodeForces/600/e.cpp b/submissions/CodeForces/600/e.cpp new file mode 100644 index 0000000..ee80691 --- /dev/null +++ b/submissions/CodeForces/600/e.cpp @@ -0,0 +1,79 @@ +#include +using namespace std; + +#ifdef DEBUG +#include "debug.cpp" +#else +#define dbg(...) +#endif + +using ll = long long; + +void small_to_large(const vector> &g, auto &&add, auto &&rem, auto &&ans, int root=0) { + vector sz(size(g)), pre(size(g)), path(size(g)), pos(size(g)); + int timer = -1; + auto tour = [&](auto &&self, int u, int p) -> void { + pre[u] = ++timer; + path[pre[u]] = u; + for (auto v : g[u]) if (v != p) self(self, v, u); + pos[u] = timer; + sz[u] = pos[u] - pre[u] + 1; + }; + tour(tour, root, -1); + auto dfs = [&](auto &&self, int u, int p = -1, bool keep=true) -> void { + int mx = -1; + for (auto v : g[u]) { + if (v != p and (mx == -1 or sz[mx] < sz[v])) + mx = v; + } + for (auto v : g[u]) if (v != p and v != mx) self(self, v, u, false); + if (mx != -1) self(self, mx, u, true); + add(u); + for (auto v : g[u]) if (v != p and v != mx) { + for (int i = pre[v]; i <= pos[v]; i++) + add(path[i]); + } + ans(u); + if (!keep) for (int i = pre[u]; i <= pos[u]; i++) rem(path[i]); + }; + dfs(dfs, root); +} + +void solve() { + int n; cin >> n; + vector c(n); + for (auto &x : c) cin >> x; + vector> g(n); + for (int i = 0; i < n-1; i++) { + int u, v; cin >> u >> v; + --u, --v; + g[u].push_back(v); + g[v].push_back(u); + } + + vector hist(n+1); + vector sum(n+1); + int best = -1;; + auto add = [&](int u) { + if (++hist[c[u]] > best) best = hist[c[u]]; + sum[hist[c[u]]] += c[u]; + }; + auto rem = [&](int u) { + sum[hist[c[u]]--] -= c[u]; + best = -1; + }; + vector res(n); + auto ans = [&](int u) { res[u] = sum[best]; }; + small_to_large(g, add, rem, ans); + for (int i = 0; i < n; i++) + cout << res[i] << " \n"[i == n-1]; +} + +int32_t main() { + cin.tie(0)->sync_with_stdio(0); + int t = 1; + // cin >> t; cin.ignore(); + for (auto i = 1; i <= t; i++) { + solve(); + } +}