Written by Anonymous
#include <bits/stdc++.h>
using namespace std;
#define max 100007
vector<int> graph[max];
long long output[max];
int colour[max], weight[max];
int n;
multiset<int> frequencia;
multiset<int>::iterator it;
vector<int>* nos[max];
int freq[max];
long long colour_sack[max];
int maior_freq;
void dfs(int u, int p){
weight[u] = 1;
for(auto v: graph[u]){
if(v != p){
dfs(v, u);
weight[u] += weight[v];
}
}
}
void sack(int u, int p, bool keep){
int son_weight = 0;
for(auto son: graph[u]){
if((!son_weight || weight[son] > weight[son_weight]) && (son != p)) son_weight = son;
}
for(auto son: graph[u]){
if(son_weight != son && son != p) sack(son, u, false);
}
if(son_weight){
sack(son_weight, u, true);
nos[u] = nos[son_weight];
}else nos[u] = new vector<int> ();
nos[u]->push_back(u);
freq[colour[u]]++;
frequencia.insert(freq[colour[u]]);
colour_sack[freq[colour[u]]] += colour[u];
for(auto son: graph[u]){
if(son != son_weight && son != p){
for(auto x: *nos[son]){
nos[u]->push_back(x);
freq[colour[x]]++;
frequencia.insert(freq[colour[x]]);
colour_sack[freq[colour[x]]] += colour[x];
}
}
}
output[u] = colour_sack[*frequencia.crbegin()];
if(!keep){
for(auto x: *nos[u]){
it = frequencia.find(freq[colour[x]]);
if(it != frequencia.end()) frequencia.erase(it);
colour_sack[freq[colour[x]]] -= colour[x];
freq[colour[x]] --;
}
}
}
int main(){
int x, y;
scanf("%d", &n);
for(int i=1; i<=n; i++) scanf("%d", &colour[i]);
for(int i=0; i<n-1; i++){
scanf("%d%d", &x, &y);
graph[x].push_back(y);
graph[y].push_back(x);
}
dfs(1,1);
sack(1,1,true);
for(int i=1; i<=n; i++){
printf("%lld ", output[i]);
}
printf("\n");
return 0;
}