说白了就是树上启发式合并,基于树剖
适用于不带修改的子树信息查询
复杂度\(O(n \log n)\)
例题CF600E
对于每个点,暴力统计轻儿子子树信息,最后再统计重儿子
如果该点为重儿子,保留信息
否则再做一遍清空信息
由于每个点到根只有\(O(\log n)\)条轻边,所以只会被统计\(O(\log n)\)次
所以复杂度是\(O(n \log n)\)
那么这题就是裸题了【其实这题有若干其它做法,之前写过一个线段树合并的做法】
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define cls(s,v) memset(s,v,sizeof(s))
#define mp(a,b) make_pair<int,int>(a,b)
#define cp pair<int,int>
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 0x3f3f3f3f;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = 0; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 1) + (out << 3) + c - 48; c = getchar();}
return flag ? out : -out;
}
LL tot,ans[maxn];
int n,sum[maxn],c[maxn],vis[maxn],maxv;
int siz[maxn],son[maxn],fa[maxn];
int h[maxn],ne = 1;
struct EDGE{int to,nxt;}ed[maxn << 1];
inline void build(int u,int v){
ed[++ne] = (EDGE){v,h[u]}; h[u] = ne;
ed[++ne] = (EDGE){u,h[v]}; h[v] = ne;
}
void dfs1(int u){
siz[u] = 1;
Redge(u) if ((to = ed[k].to) != fa[u]){
fa[to] = u; dfs1(to);
siz[u] += siz[to];
if (!son[u] || siz[to] > siz[son[u]]) son[u] = to;
}
}
void cal(int u,int t){
sum[c[u]] += t;
if (t > 0 && sum[c[u]] >= maxv){
if (sum[c[u]] > maxv) maxv = sum[c[u]],tot = 0;
tot += c[u];
}
Redge(u) if (!vis[to = ed[k].to] && (to != fa[u]))
cal(to,t);
}
void dfs2(int u,int remain){
Redge(u) if ((to = ed[k].to) != fa[u] && to != son[u])
dfs2(to,0);
if (son[u]) dfs2(son[u],1),vis[son[u]] = true;
cal(u,1); ans[u] = tot;
if (son[u]) vis[son[u]] = false;
if (!remain) cal(u,-1),tot = maxv = 0;
}
int main(){
n = read();
REP(i,n) c[i] = read();
for (int i = 1; i < n; i++) build(read(),read());
dfs1(1);
dfs2(1,0);
REP(i,n) printf("%I64d ",ans[i]);
return 0;
}