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
| #include <cstdio> using namespace std; typedef long long LL; const int N = 1e5 + 10, M = 2e5 + 10; LL mx, sum, ans[N]; int n, c[N], cnt[N]; int p[N], sz[N], son[N]; int idx, hd[N], nxt[M], edg[M]; void dfs1(int x) { sz[x] = 1; son[x] = -1; for (int i = hd[x]; ~i; i = nxt[i]) { if (p[edg[i]]) continue; p[edg[i]] = x; dfs1(edg[i]); sz[x] += sz[edg[i]]; if (son[x] == -1 || sz[edg[i]] > sz[son[x]]) son[x] = edg[i]; } } void update(int x, int op, int avoid) { cnt[c[x]] += op; if (cnt[c[x]] > mx) { mx = cnt[c[x]]; sum = c[x]; } else if (cnt[c[x]] == mx) sum += c[x]; for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != avoid && edg[i] != p[x]) update(edg[i], op, avoid); } void dfs2(int x, int op) { for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != son[x] && edg[i] != p[x]) dfs2(edg[i], 0); if (~son[x]) dfs2(son[x], 1); update(x, 1, son[x]); ans[x] = sum; if (!op) { update(x, -1, 0); sum = mx = 0; } } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1; i <= n; i++) scanf("%d", &c[i]); for (int i = 1, a, b; i < n; i++) { scanf("%d%d", &a, &b); add(a, b); add(b, a); } p[1] = -1; dfs1(1); dfs2(1, 1); for (int i = 1; i <= n; i++) printf("%lld ", ans[i]); return 0; }
|