以CF600E为例,其他的题大致框架都差不多这样
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define endl '\n'
#define int long long
const int maxn = 1e5 + 5;
const int maxm = maxn << 1;
int a[maxn],n,son[maxn],ans[maxn],sz[maxn],num[maxn],now,skip,maxx;
int head[maxn],nex[maxm],v[maxm],w[maxm],cnt,dis[maxn],vis[maxn];
void add(int x,int y){
nex[++cnt] = head[x];
head[x] = cnt;
v[cnt] = y;
}
void dfs1(int node,int fa){
sz[node] = 1;
for (int i = head[node]; i; i = nex[i]) {
int to = v[i];
if (to == fa) continue;
dfs1(to,node);
sz[node] += sz[to];
if (!son[node] || sz[son[node]] < sz[to]) son[node] = to;
}
}
void cal(int node,int fa,int val){//只需要修改计算子树贡献的函数就可以
num[a[node]] += val;
if (num[a[node]] == maxx) now += a[node];
else if (num[a[node]] > maxx){
maxx = num[a[node]];
now = a[node];
}
for (int i = head[node]; i; i = nex[i]) {
int to = v[i];
if (to == fa || to == skip) continue;
cal(to,node,val);
}
}
void dfs(int node,int fa,bool clear){
for (int i = head[node]; i; i = nex[i]) {
int to = v[i];
if (to == fa || to == son[node]) continue;
dfs(to,node, true);
}
if (son[node]) dfs(son[node],node, false);
skip = son[node];
//下面这里也需要看情况修改
cal(node,fa,1);
skip = 0;
ans[node] = now;
if (clear){
cal(node,fa,-1);
now = maxx = 0;
}
}
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
for (int i = 1; i <= n - 1; ++i) {
int x,y;
cin >> x >> y;
add(x,y);
add(y,x);
}
dfs1(1,0);
dfs(1,0, false);
for (int i = 1; i <= n; ++i) {
cout << ans[i] << ' ';
}
}