dsu on tree
先分轻重儿子
先处理轻边,再处理重儿子
再加上轻儿子的答案
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#pragma GCC optimize(2)
#define inf 2147483647
#define ls rt<<1
#define rs rt<<1|1
#define lson ls,nl,mid,l,r
#define rson rs,mid+1,nr,l,r
#define N 1000010
#define For(i,a,b) for(long long i=a;i<=b;++i)
#define p(a) putchar(a)
#define g() getchar() using namespace std;
long long n,col[N],son[N],size[N],cnt[N],Max,Son;
long long sum,ans[N],x,y; struct node{
long long n;
node *next;
}*e[N]; void in(long long &x){
long long y=;char c=g();x=;
while(c<''||c>''){if(c=='-')y=-;c=g();}
while(c<=''&&c>=''){ x=(x<<)+(x<<)+c-'';c=g();}
x*=y;
}
void o(long long x){
if(x<){p('-');x=-x;}
if(x>)o(x/);
p(x%+'');
} void push(long long x,long long y){
node *p;
p=new node();
p->n=y;
if(e[x]==)
e[x]=p;
else{
p->next=e[x]->next;
e[x]->next=p;
}
} void dfs(long long x,long long fa){//重儿子
size[x]=;
for(node *i=e[x];i;i=i->next){
if(i->n==fa) continue;
dfs(i->n,x);
size[x]+=size[i->n];
if(size[i->n]>size[son[x]])
son[x]=i->n;
}
} void add(long long x,long long fa,long long val){
cnt[col[x]]+=val;
if(cnt[col[x]]>Max){
Max=cnt[col[x]];
sum=col[x];
}
else
if(cnt[col[x]]==Max)
sum+=col[x];
for(node *i=e[x];i;i=i->next){
if(i->n==fa||i->n==Son) continue;
add(i->n,x,val);
}
} void dfs2(long long x,long long fa,long long opt){
for(node *i=e[x];i;i=i->next){
if(i->n==fa) continue;
if(i->n!=son[x]) dfs2(i->n,x,);
}
if(son[x]){
dfs2(son[x],x,);
Son=son[x];
}
add(x,fa,);
Son=;
ans[x]=sum;
if(!opt){
add(x,fa,-);
sum=;
Max=;
}
} int main(){
in(n);
For(i,,n)
in(col[i]);
For(i,,n-){
in(x);in(y);
push(x,y);
push(y,x);
}
dfs(,);
dfs2(,,);
For(i,,n)
o(ans[i]),p(' ');
return ;
}