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 73 74 75 76 77 78 79 80 81 82
| #include <bits/stdc++.h> #define LL long long using namespace std; const int N = 1e5 + 5; int n; int h[N], idx; struct Edge { int ne, ver; } e[N << 1]; int c[N], cnt[N], mx; LL ans[N], sum; int si[N], h_son[N]; void add(int x, int y) { e[idx] = (Edge){h[x], y}, h[x] = idx++; } void dfs1(int x, int fa) { si[x] = 1; for (int i = h[x], y; i != -1; i = e[i].ne) { y = e[i].ver; if (y == fa) continue; dfs1(y, x); si[x] += si[y]; if (si[y] > si[h_son[x]]) h_son[x] = y; } } void update(int x, int fa, int dt, int pass) { int _c = c[x]; cnt[_c] += dt; if (cnt[_c] > mx) mx = cnt[_c], sum = _c; else if (cnt[_c] == mx) sum += _c; for (int i = h[x], y; i != -1; i = e[i].ne) { y = e[i].ver; if (y == fa || y == pass) continue; update(y, x, dt, pass); } } void dfs(int x, int fa, int op) { for (int i = h[x], y; i != -1; i = e[i].ne) { y = e[i].ver; if (y == fa || y == h_son[x]) continue; dfs(y, x, 0); } if (h_son[x]) dfs(h_son[x], x, 1); update(x, fa, 1, h_son[x]); ans[x] = sum; if (!op) update(x, fa, -1, 0), mx = sum = 0; } int main() { scanf("%d%d", &n); for (int i = 1; i <= n; ++i) h[i] = -1; idx = 0; for (int i = 1; i <= n; ++i) scanf("%d", &c[i]); for (int i = 1, u, v; i < n; ++i) { scanf("%d%d", &u, &v); add(u, v), add(v, u); } dfs1(1, -1); dfs(1, -1, 1); for (int i = 1; i <= n; i++) printf("%lld ", ans[i]); return 0; }
|