fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 1e5 + 5;
  12.  
  13. int n;
  14. int c[N];
  15. vector<int> adj[N];
  16.  
  17. map<int, int> cnt[N]; // cnt[u][c] = Số đỉnh có mã màu c trong cây con gốc u
  18. int mx_cnt[N]; // mx_cnt[u] = Số lần xuất hiện của mã màu có số lần xuất hiện nhiều nhất trong cây con gốc u
  19. ll sum[N]; // sum[u] = Tổng của những mã màu có số lần xuất hiện nhiều nhất trong cây con gốc u
  20. ll ans[N]; // ans[u] = Đáp án của cây con gốc u
  21.  
  22. void dfs(int u, int p) {
  23. cnt[u][c[u]]++;
  24. mx_cnt[u] = 1;
  25. sum[u] = c[u];
  26.  
  27. for (int v : adj[u]) {
  28. if (v == p) continue;
  29.  
  30. dfs(v, u);
  31.  
  32. if (cnt[u].size() < cnt[v].size()) {
  33. swap(cnt[u], cnt[v]);
  34. swap(mx_cnt[u], mx_cnt[v]);
  35. swap(sum[u], sum[v]);
  36. }
  37.  
  38. for (auto it : cnt[v]) {
  39. int new_cnt = cnt[u][it.first] + it.second;
  40. cnt[u][it.first] = new_cnt;
  41.  
  42. if (mx_cnt[u] < new_cnt) {
  43. mx_cnt[u] = new_cnt;
  44. sum[u] = it.first;
  45. }
  46. else if (mx_cnt[u] == new_cnt) {
  47. sum[u] += it.first;
  48. }
  49. }
  50. }
  51.  
  52. ans[u] = sum[u];
  53. }
  54.  
  55. int main() {
  56. ios::sync_with_stdio(false);
  57. cin.tie(nullptr);
  58. cin >> n;
  59.  
  60. for (int u = 1; u <= n; u++) cin >> c[u];
  61.  
  62. for (int i = 0; i < n - 1; i++) {
  63. int u, v;
  64. cin >> u >> v;
  65. adj[u].push_back(v);
  66. adj[v].push_back(u);
  67. }
  68.  
  69. dfs(1, -1);
  70.  
  71. for (int u = 1; u <= n; u++) {
  72. cout << ans[u] << ' ';
  73. }
  74. }
Success #stdin #stdout 0.01s 11120KB
stdin
4
1 2 3 4
1 2
2 3
2 4
stdout
10 9 3 4