#include <algorithm> #include <iostream> #include <cstring> #include <iomanip> #include <cstdlib> #include <sstream> #include <cstdio> #include <string> #include <vector> #include <cctype> #include <stack> #include <queue> #include <deque> #include <cmath> #include <map> #include <set>
#define I inline #define db double #define ll long long #define pb push_back #define MP make_pair #define ldb long double #define ull unsigned long long #define PII pair<int , int> #define PIL pair<int , long long> #define PSL pair<string , long long> #define PLL pair<long long , long long> #define all(x) (x).begin() , (x).end() #define copy(a , b) memcpy(a , b , sizeof(b)) #define clean(a , b) memset(a , b , sizeof(a)) #define rep(i , l , r) for (int i = (l); i <= (r); i ++) #define per(i , r , l) for (int i = (r); i >= (l); i --) #define PE(i , x) for(int i = head[x]; i; i = edge[i].last) #define DEBUG(x) std :: cerr << #x << '=' << x << std :: endl
using namespace std;
const int N = 10001; const int M = 100001; const int HA = 998244353; const int INF = 2047483647; const long long INFL = 9023372036854775807;
int n;
struct Edge{ int to , last; }edge[M << 1];
int edge_num; int head[M << 1];
I void add_edge(int from , int to){ edge[++ edge_num] = (Edge){to , head[from]}; head[from] = edge_num; edge[++ edge_num] = (Edge){from , head[to]}; head[to] = edge_num; }
int size[M] , son[M];
int dfs(int x , int fa){ size[x] = 1; int maxn = -1; PE(i , x){ int to = edge[i].to; if(to == fa) continue; size[x] += dfs1(to , x); if(size[to] > maxn){ maxn = size[x]; son[x] = to; } } return size[x]; }
ll maxn , sum , SON , col[M] , cnt[M];
void add(int x , int fa , int val){ cnt[col[x]] += val; if(cnt[col[x]] > maxn) maxn = cnt[col[x]] , sum = col[x]; else if(cnt[col[x]] == maxn) sum += col[x]; PE(i , x){ int to = edge[i].to; if(to == fa || to == SON) continue; add(to , x , val); } }
ll ans[M];
void calc(int x , int fa , int opt){ PE(i , x){ int to = edge[i].to; if(to == fa) continue; else if(to != son[x]){ calc(to , x , 0); } } if(son[x]) calc(son[x] , x , 1) , SON = son[x];
add(x , fa , 1); SON = 0; ans[x] = sum; if(opt == 0) add(x , fa , -1) , maxn = 0; }
int main() { #ifdef LOCAL freopen("try.in" , "r" , stdin); freopen("try1.out" , "w" , stdout); #endif scanf("%d" , &n); rep(i , 1 , n){ scanf("%d" , &col[i]); } int u , v; rep(i , 1 , n - 1){ scanf("%d%d" , &u , &v); add_edge(u , v); } dfs(1 , 0); calc(1 , 0 , 1); rep(i , 1 , n){ printf("%lld " , ans[i]); }
return 0; }
|