CSES - Shared codeLink to this code: https://cses.fi/paste/ffc22cc3a4381ee76676d1/
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <string>
#include <algorithm>
#include <utility>   
#define int long long
using namespace std;

const int N = 2e5 + 5;
 
vector<int> adj[N];
int n, col[N], distinct[N];

set<int> colors[N];
 

 
void dfs(int node, int par = 0) {
 
   colors[node].insert(col[node]);
 
   for(int child : adj[node]) {
      if(child != par) {
         dfs(child, node);
         if(colors[child].size() > colors[node].size())
           swap(colors[child], colors[node]);
         for(int val: colors[child])
           colors[node].insert(val);
      }
   }
   
   distinct[node] = colors[node].size();
}
 
 
int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
  #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
  #endif  
 
  int x, y;
  cin >> n;
 
  for(int i = 1; i <= n; i++){
     cin >> col[i];
  }
 
  for(int i = 1; i < n; i++){
    cin >> x >> y;
    adj[x].push_back(y);
    adj[y].push_back(x);
  }
 
  dfs(1);
 
  for(int i = 1; i <= n; i++){
     cout << distinct[i] << ' ';
  }
 
 return 0;
}