1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include "iostream" #include "algorithm" #include "cstring" #include "cstdio" #include "cmath" #include "vector" #include "map" #include "set" #include "bitset" #include "queue" using namespace std; #define MAXN 200006
#define rep(i, a, b) for (int i = (a), i##end = (b); i <= i##end; ++i) #define per(i, a, b) for (int i = (a), i##end = (b); i >= i##end; --i) #define pii pair<int,int> #define fi first #define se second #define mp make_pair #define pb push_back #define eb emplace_back #define vi vector<int> #define all(x) (x).begin() , (x).end() #define mem( a ) memset( a , 0 , sizeof a ) #define P 998244353 typedef long long ll; int n , m , z , q , blo; int A[MAXN]; vector<int> G[MAXN];
int L[MAXN] , R[MAXN] , bac[MAXN] , siz[MAXN] , clo; void dfs1( int u , int fa ) { siz[u] = 1; L[u] = ++ clo; bac[clo] = u; for( int v : G[u] ) if( v != fa ) dfs1( v , u ) , siz[u] += siz[v]; R[u] = clo; } long long res[MAXN] , ans; int cnt[MAXN] , mxc; void dfs( int u , int fa , int ke ) { int mx = 0; for( int v : G[u] ) if( v != fa && ( !mx || siz[v] > siz[mx] ) ) mx = v; for( int v : G[u] ) if( v != fa && v != mx ) dfs( v , u , 0 ); if( mx ) dfs( mx , u , 1 ); ++ cnt[A[u]]; if( cnt[A[u]] > mxc ) mxc = cnt[A[u]] , ans = A[u]; else if( cnt[A[u]] == mxc ) ans += A[u]; for( int v : G[u] ) if( v != fa && v != mx ) for( int i = L[v] ; i <= R[v] ; ++ i ) { int c = A[bac[i]]; ++ cnt[c]; if( cnt[c] > mxc ) mxc = cnt[c] , ans = c; else if( cnt[c] == mxc ) ans += c; } res[u] = ans; if( !ke ) { for( int i = L[u] ; i <= R[u] ; ++ i ) -- cnt[A[bac[i]]]; ans = mxc = 0; } }
void solve() {
cin >> n; rep( i , 1 , n ) scanf("%d",&A[i]); int u , v; rep( i , 2 , n ) scanf("%d%d",&u,&v) , G[u].pb( v ) , G[v].pb( u ); dfs1( 1 , 1 ) , dfs( 1 , 1 , 1 ); rep( i , 1 , n ) printf("%lld%c",res[i]," \n"[i==n]); }
signed main() {
solve(); }
|