#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int read(){
int x = 0,f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
inline void write(int x)
{
char F[200];
int tmp = x > 0 ? x : -x;
if(x<0) putchar('-');
int cnt = 0;
while(tmp > 0){
F[cnt++] = tmp%10+'0';
tmp /= 10;
}
while(cnt > 0) putchar(F[--cnt]);
putchar('\n');
}
int n, c[100005], u, v, ans[100005], siz[100005], he[100005], s[100005], maxn, maxx;
vector<int> d[100005];
void dfs(int x, int fa){
siz[x] = 1;
int tmp = 0;
for(int i = 0; i < d[x].size(); ++i){
int y = d[x][i];
if(y == fa) continue;
dfs(y, x);
siz[x] += siz[y];
if(siz[y] > tmp){
tmp = siz[y];
he[x] = y;
}
}
}
void calc(int x, int fa){
s[c[x]]++;
if(s[c[x]] > maxn){
maxn = s[c[x]];
maxx = c[x];
}
else if(s[c[x]] == maxn) maxx += c[x];
for(int i = 0; i < d[x].size(); ++i){
int y = d[x][i];
if(y == fa || y == he[x]) continue;
calc(y, x);
}
}
void delc(int x, int fa){
s[c[x]]--;
for(int i = 0; i < d[x].size(); ++i){
int y = d[x][i];
if(y == fa) continue;
delc(y, x);
}
}
void dsu(int x, int fa, int op){
for(int i = 0; i < d[x].size(); ++i){
int y = d[x][i];
if(y == fa || y == he[x]) continue;
dsu(y, x, 0);
}
if(he[x]) dsu(he[x], x, 1);
calc(x, fa);
ans[x] = maxx;
if(op) return ;
delc(x, fa);
maxx = maxn = 0;
}
int main(){
n = read();
for(int i = 1; i <= n; ++i){
c[i] = read();
}
for(int i = 1; i < n; ++i){
u = read(), v = read();
d[u].push_back(v);
d[v].push_back(u);
}
dfs(1, 0);
dsu(1, 0, 1);
for(int i = 1; i <= n; ++i){
printf("%d ", ans[i]);
}
return 0;
}
第二个样例出了第一个点都对,第一个点输出 3。
求调,谢谢/bx