Untitled

mail@pastecode.io avatar
unknown
c_cpp
24 days ago
1.6 kB
8
Indexable
Never
#include <bits/stdc++.h>
using namespace std;
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define LSB(i) ((i) & (-i))
#define ll long long
const int dx[]{-1,1,0,0,-1,-1,1,1};
const int dy[]{0,0,1,-1,-1,1,-1,1};
const int MOD = 1e9+7;
#define int ll


const int N = 2e5+5;

std::vector<int> G[N];
int col[N], ans[N], sz[N];
set<int> vec[N];

int dfs_size(int u, int p){
    sz[u] = 1;
    for(int v : G[u]){
        if(v==p) continue;
        dfs_size(v, u);
        sz[u] += sz[v];
    }
    return sz[u];
}
void dfs(int u, int p, bool keep){
    int mx = 0, big = -1;
    for(int v : G[u]){
        if(v==p) continue;
        if(vec[v].size() > mx) mx = vec[v].size(), big = v;
    }
    for(int v : G[u]){
        if(v==p || v==big) continue;
        dfs(v, u, 0);
    }
    if(big != -1){
        dfs(big, u, 1);
        swap(vec[u], vec[big]);
    }
    vec[u].insert(col[u]);
    for(int v : G[u]){
        if(v==p || v==big) continue;
        for(int x : vec[v]) vec[u].insert(x);
    }
    ans[u] = vec[u].size();
}   
void solve(int testCase)  {
    int n;
    cin >> n;
    for(int i = 1; i <= n; ++i) cin >> col[i];
    for(int i = 1; i < n; ++i){
        int a, b;
        cin >> a >> b;
        G[a].push_back(b);
        G[b].push_back(a);
    }  
    dfs_size(1, 0);
    dfs(1, 0, 1);
    for(int i = 1; i <= n; ++i) cout << ans[i] << " ";
} 

int32_t main(){
    fastio();  
    int t = 1;
  //   cin >> t;
    for(int i = 1; i <= t; ++i){
        solve(i);
    }
    return 0;
}
Leave a Comment