板子
void dfs_pre(int x, int f) {
L[x]=++*L, no[*L]=x, sz[x] = 1;
for (auto &&e:g[x]) if (e.to!=f) {
int y = e.to;
fa[y]=f, dfs_pre(y,x), sz[x]+=sz[y];
if (sz[y]>sz[son[x]]) son[x]=y;
}
R[x]=*L;
}
void dfs(int x) {
for (auto &&e:g[x]) if (e.to!=fa[x]&&e.to!=son[x]) dfs(e.to);
if (son[x]) dfs(son[x]);
for (auto &&e:g[x]) if (e.to!=fa[x]&&e.to!=son[x]) {
REP(z,L[e.to],R[e.to]) add(no[z],1);
}
if (son[fa[x]]!=x) REP(z,L[x],R[x]) add(no[z],0);
}
练习1. Lomsat gelral CodeForces - 600E
大意: 给定有根树, 对于每个点$x$, 询问$x$子树内颜色最多的点的颜色, 若有同样多的输出颜色和.
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head
const int N = 1e6+10;
int n;
vector<int> g[N];
int a[N], no[N], sz[N], fa[N], son[N];
int L[N], R[N], tot[N], ma;
ll ans[N], cnt;
void dfs_pre(int x, int f) {
L[x]=++*L, no[*L]=x, sz[x] = 1;
for (auto &&y:g[x]) if (y!=f) {
fa[y]=x, dfs_pre(y,x), sz[x]+=sz[y];
if (sz[y]>sz[son[x]]) son[x]=y;
}
R[x]=*L;
}
void add(int x) {
++tot[a[x]];
if (tot[a[x]]>ma) ma=tot[a[x]],cnt=a[x];
else if (tot[a[x]]==ma) cnt+=a[x];
}
void dfs(int x) {
for (auto &&y:g[x]) if (y!=fa[x]&&y!=son[x]) dfs(y);
if (son[x]) dfs(son[x]);
for (auto &&y:g[x]) if (y!=fa[x]&&y!=son[x]) {
REP(z,L[y],R[y]) add(no[z]);
}
add(x), ans[x] = cnt;
if (son[fa[x]]!=x) {
cnt=ma=0;
REP(z,L[x],R[x]) tot[a[no[z]]]=0;
}
}
int main() {
scanf("%d", &n);
REP(i,1,n) scanf("%d", a+i);
REP(i,2,n) {
int u, v;
scanf("%d%d", &u, &v);
g[u].pb(v),g[v].pb(u);
}
dfs_pre(1,0),dfs(1);
REP(i,1,n) printf("%lld ",ans[i]);hr;
}