第一次AC这道题,是三年前的一个下午,也许晚上也说不定。当时使用的
# include "bits/stdc++.h"
using namespace std;
constexpr int N = 1e5 + 3;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n;
cin >> n;
vector<int> col(n + 1);
for(int i = 1; i <= n; ++i) cin >> col[i];
vector G(n + 1, vector<int>());
for(int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
struct node {
int l, r, tot;
long long sum;
};
# define ls t[rt].l
# define rs t[rt].r
# define lson t[rt].l, l, mid
# define rson t[rt].r, mid + 1, r
vector t(N * 50) ;
auto push_up = [&](int rt) -> void {
if(t[ls].tot == t[rs].tot) {
t[rt].tot = t[ls].tot;
t[rt].sum = t[ls].sum + t[rs].sum;
}
else if(t[ls].tot > t[rs].tot) {
t[rt].tot = t[ls].tot;
t[rt].sum = t[ls].sum;
}
else {
t[rt].tot = t[rs].tot;
t[rt].sum = t[rs].sum;
}
};
vector<int> rt(n + 1, 0);
int tree_index = n; // 1~n node has their names
auto update = [&](auto update, int &rt, int l, int r, int x) -> void {
if(!rt) rt = ++tree_index;
if(l == r) {
++t[rt].tot;
t[rt].sum = l;
return;
}
int mid = l + r >> 1;
if(x <= mid)
update(update, lson, x);
else
update(update, rson, x);
push_up(rt);
};
auto merge = [&](auto merge, int x, int y, int l, int r) -> int {
if(!x || !y) return x | y;
if(l == r) {
t[x].tot += t[y].tot;
t[x].sum = l;
return x;
}
int mid = l + r >> 1;
t[x].l = merge(merge, t[x].l, t[y].l, l, mid);
t[x].r = merge(merge, t[x].r, t[y].r, mid + 1, r);
push_up(x);
return x;
};
vector<long long> ans(n + 1);
auto dfs = [&](auto dfs, int u, int father) -> void {
for(auto v : G[u]) {
if(v == father) continue;
dfs(dfs, v, u);
merge(merge, u, v, 1, n);
}
update(update, u, 1, n, col[u]);
ans[u] = t[u].sum;
};
dfs(dfs, 1, 0);
for(int i = 1; i <= n; ++i) cout << ans[i] << " ";
return 0;
}