跳到正文

个人记录

树上启发式合并例题

another_world约 24 分钟
原文
文章信息与版本

文章信息

发布
2023年11月3日
收录
2025年12月12日
更新
2026年10月25日
篇幅
约 24 分钟

版本

  1. v2当前
  2. v1

DSU ON TREE

  • 并查集的按秩合并作为常见的启发式合并,本质是对于两个集合进行合并,考虑将秩较小的集合合并至秩较大的集合,发现秩较小的集合的秩至少增至二倍,那么每个元素至多合并 log⁡\log 级别次,从而保证时间复杂度

  • 对于树上启发式合并,往往需要统计以每个树节点为根的子树的某种贡献,考虑将以轻儿子为根的子树贡献合并至以重儿子为根的子树贡献,递归遍历树进行处理


例题:[HNOI2009] 梦幻布丁

  1. 作为启发式合并的经典题,显然将集合大小较小的颜色合并至集合大小较大的颜色

  2. 考虑链式前向星维护颜色集合


Code:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
const int maxn=1e6+10;
int n,m,c[N],dfn[maxn],ans;
int siz[maxn],head[maxn],nt[maxn],st[maxn];
void merge(int x,int y) {
	for(int i=head[x]; i; i=nt[i]) ans-=(c[i-1]==y)+(c[i+1]==y);
	for(int i=head[x]; i; i=nt[i]) c[i]=y;
	nt[st[x]]=head[y],head[y]=head[x],siz[y]+=siz[x];
	st[x]=head[x]=siz[x]=0;
}
int main() {
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++) {
    	scanf("%d",&c[i]); dfn[c[i]]=c[i];
    	if(c[i]!=c[i-1]) ans++;
    	if(!head[c[i]]) st[c[i]]=i;
		siz[c[i]]++,nt[i]=head[c[i]],head[c[i]]=i;
	}
	for(int op,i=1; i<=m; i++) {
		scanf("%d",&op);
		if(op==2) printf("%d\n",ans);
		else {
			int x,y;
			scanf("%d%d",&x,&y);
			if(x==y) continue;
			if(siz[dfn[x]]>siz[dfn[y]]) swap(dfn[x],dfn[y]);
			if(!siz[dfn[x]]) continue;
			merge(dfn[x],dfn[y]);
		}
	}
	return 0;
}

例题:CF 600-E

  1. 考虑遍历树上节点,开桶统计以当前节点为根的子树内每种颜色的出现次数,显然统计完成当前子树的贡献后,要求我们清空桶,避免对以兄弟节点为根的子树的贡献统计造成影响,然而在统计以其父亲节点为根的子树的贡献时,又需要重新遍历统计当前子树的贡献

  2. 发现当前节点的最后遍历的儿子节点 vv,以 vv 为根的子树的贡献没有必要清空,只需要再遍历统计以其余儿子为根的子树,考虑令 vv 为重儿子,保证时间复杂度 O(nlog⁡n)O(n \log n)

  3. 时间复杂度证明:对于每个树节点的遍历次数为其到根节点的路径上的轻边数量,由于树上任意节点的轻边数量至多 log⁡n\log n,则有时间复杂度 O(nlog⁡n)O(n\log n),有些含糊,感性理解

  4. 以上即为树上启发式合并的大致思路,对于这道题,只需要再维护最大出现次数即可解决


Code:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
int n,c[N],cnt[N];
ll ans[N];
struct EDGE {
	int v,lt;
}E[N*2];
int head[N],tot;
void add(int u,int v) {
	E[++tot].v=v;
	E[tot].lt=head[u];
	head[u]=tot;
}
int siz[N],hson[N];
void dfs1(int x,int father) {
	siz[x]=1;
	int h=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father) continue;
		dfs1(y,x);
		siz[x]+=siz[y];
		if(siz[y]>siz[h]) h=y;
	}
	hson[x]=h;
}
void clr(int x,int father) {
    cnt[c[x]]--;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=father) clr(y,x);
	}
}
ll res,maxx;
void dfs3(int x,int father,int h) {
	cnt[c[x]]++;
	if(cnt[c[x]]>=maxx) {
		if(cnt[c[x]]==maxx) res+=c[x];
		else res=c[x],maxx=cnt[c[x]];
	}
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=father && y!=h) dfs3(y,x,h);
	}
}
void dfs2(int x,int father) {
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father || y==hson[x]) continue;
		dfs2(y,x);
		clr(y,x);
		res=maxx=0;
	}
	if(hson[x]) dfs2(hson[x],x);
	dfs3(x,father,hson[x]);
    ans[x]=res;
}
int main() {
    scanf("%d",&n);
    for(int i=1; i<=n; i++) scanf("%d",&c[i]);
    for(int x,y,i=1; i<n; i++) {
    	scanf("%d%d",&x,&y);
    	add(x,y);
    	add(y,x);
	}
	dfs1(1,0);
	dfs2(1,0);
	for(int i=1; i<=n; i++) printf("%lld ",ans[i]);
	return 0;
}

例题:CF 741-D

  1. 考虑一个字符串重新排序后可以构成回文串,当且仅当每种字符出现次数均为偶数次或者仅有一种字符出现奇数次,由于字符至多 2222 种,而且每种字符只需考虑出现次数的奇偶性,考虑二进制状态压缩和异或操作

  2. 设 disxdis_{x} 表示节点 xx 到根节点的路经上的字符出现次数的奇偶性的集合状态,那么对于任意路经 (x,y)(x,y) 的集合状态,则有 disx⊕disy⊕dislca(x,y)⊕dislca(x,y)=disx⊕disydis_{x} \oplus dis_{y} \oplus dis_{lca(x,y)} \oplus dis_{lca(x,y)}=dis_{x} \oplus dis_{y},

  3. 考虑合法路径的判断,对于目标集合状态 maskmask 显然有且仅有 2323 种,那么对于合法路径 (x,y)(x,y),则有:disx⊕disy=maskdis_{x} \oplus dis_{y}=mask

  4. 思考如何统计以当前节点为根的子树内的合法路径,类似点分治的思想,考虑经过当前节点的合法路径,即统计满足以下两个要求的点对 (x,y)(x,y) 的数量:

  • 节点 x,yx,y 不在当前节点为根的同一儿子子树
  • disx⊕disy=maskdis_{x} \oplus dis_{y}=mask
  1. 具体实现,开桶统计前缀儿子子树内的所有 disdis 值的最大深度节点,那么依次遍历当前节点为根的各个儿子子树,对于当前儿子子树内节点 xx,查询前缀儿子子树内满足 disx⊕mask=disydis_{x} \oplus mask = dis_{y} 的最大深度的节点 yy,同时维护合法路经 (x,y)(x,y) 的最大长度,最后把当前儿子子树的节点信息累积统计至前缀儿子子树

  2. 现在解决了如何统计以当前节点为根的子树的贡献,那么树上启发式合并维护统计以每个节点为根的子树的贡献的过程,显然保留以重儿子为根的子树的桶的信息,时间复杂度 O(nlog⁡n)O(n\log n)


Code:

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e6+10;
const int N=5e5+10;
const int T=23;
int n,d[N],fa[N],ans[N];
int g[T];
struct EDGE {
	int v,lt;
}E[N*2];
int head[N],tot;
void add(int u,int v) {
	E[++tot].v=v;
	E[tot].lt=head[u];
	head[u]=tot;
}
int siz[N],dep[N],hson[N];
void dfs1(int x) {
	siz[x]=1; dep[x]=dep[fa[x]]+1;
	int h=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==fa[x]) continue;
		d[y]^=d[x];
		dfs1(y);
		siz[x]+=siz[y];
		if(siz[y]>siz[h]) h=y;
	}
	hson[x]=h;
}
int cnt[maxn],res;
void dfs3(int x,int root,int sign) {
	if(sign) cnt[d[x]]=max(cnt[d[x]],dep[x]);
	else for(int i=0; i<T; i++)
		    if(cnt[d[x]^g[i]]) res=max(res,cnt[d[x]^g[i]]+dep[x]-dep[root]*2);
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==fa[x]) continue;
		dfs3(y,root,sign);
	}
}
void init(int x) {
	cnt[d[x]]=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==fa[x]) continue;
		init(y);
	}
}
void dfs2(int x) {
	int h=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==fa[x] || y==hson[x]) continue;
		dfs2(y);
		init(y);
		res=0;
	}
	if(hson[x]) dfs2(hson[x]);
	cnt[d[x]]=max(cnt[d[x]],dep[x]);
	for(int i=0; i<T; i++)
		if(cnt[d[x]^g[i]]) res=max(res,cnt[d[x]^g[i]]+dep[x]-dep[x]*2);
	for(int i=head[x]; i; i=E[i].lt) { // 类似点分治的思想,当前子树内仅考虑经过 x 根节点的路经
		int y=E[i].v;
		if(y==fa[x] || y==hson[x]) continue;
		dfs3(y,x,0);
		dfs3(y,x,1);
	}
	ans[x]=res;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=fa[x]) ans[x]=max(ans[x],ans[y]);
	}
}
void prework() {
	for(int i=0; i<T; i++) {
		if(!i) g[i]=0;
		else g[i]=1<<(i-1);
	}
}
int main() {
	prework();
    scanf("%d",&n);
    for(int i=2; i<=n; i++) {
    	char s[2];
    	scanf("%d%s",&fa[i],&s);
    	add(fa[i],i);
		d[i]=(1<<(s[0]-'a'));
	}
	dfs1(1);
	dfs2(1);
	for(int i=1; i<=n; i++) printf("%d ",ans[i]);
	return 0;
}

例题:树上统计 treecnt

  1. 考虑每条边会对哪些区间产生贡献,即哪些连续编号节点区间相互联通需要经过当前边,发现难以统计,正难则反,那么对于连续编号节点区间相互联通不需要经过当前边,即当前边将树划分的两个联通块内的连续编号节点区间

  2. 我们可以遍历树,统计以每个节点为根的子树内外的连续编号节点区间,考虑通过 0101 序列统计所有编号节点的信息,序列第 ii 个元素为 11 表示当前子树内存在编号 ii 节点,00 则表示当前子树外存在编号 ii 节点,那么以每个节点为根的子树内外的连续编号节点区间转化为以每个节点为根的子树的 0101 序列的连续 0101 区间

  3. 那么还是树上启发式合并维护统计以每个节点为根的子树的贡献的过程,显然保留以重儿子为根的子树的 0101 序列,发现时间复杂度不允许我们暴力遍历以每个节点为根的子树的 0101 序列以统计贡献,考虑动态维护统计 0101 序列的连续 0101 区间

  4. 考虑 0101 序列初始所有元素均为 00,合并以轻儿子为根的子树的节点信息的过程中,序列中的元素 00 不断变成元素 11,连续 00 区间不断断离,连续 11 区间不断合并,那么并查集维护连续 11 区间,setset 维护所有连续 00 区间左右端点即可


Code:

C++
#include<bits/stdc++.h> // 当前子树内并查集维护,当前子树外 set 维护
using namespace std;
typedef long long ll;
const int N=1e5+10;
int n;
ll ans;
struct EDGE {
	int v,lt;
}E[N*2];
int head[N],tot;
void add(int u,int v) {
	E[++tot].v=v;
	E[tot].lt=head[u];
	head[u]=tot;
}
int siz[N],hson[N];
void dfs1(int x,int father) {
	siz[x]=1;
	int h=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father) continue;
		dfs1(y,x);
		siz[x]+=siz[y];
		if(siz[y]>siz[h]) h=y;
	}
	hson[x]=h;
}
int cnt[N],dfn[N],d[N];
ll val(ll x) { return x*(x-1)/2ll; }
int get(int x) { return x==dfn[x]?x:dfn[x]=get(dfn[x]); }
set<int> out;
ll res1,res0;
void calc(int x) {
    cnt[x]=1;
    if(cnt[x-1]) {
    	int l=get(x-1),r=get(x);
    	res1+=(ll)d[l]*d[r];
    	dfn[l]=r,d[r]+=d[l];
	}
	if(cnt[x+1]) {
		int l=get(x),r=get(x+1);
		res1+=(ll)d[l]*d[r];
		dfn[l]=r,d[r]+=d[l];
	}

	out.insert(x);
	set<int>::iterator it=out.find(x),pre=it,nxt=++it;
	--pre;
	res0-=val((ll)(*nxt-*pre-1));
	res0+=val((ll)(x-*pre-1))+val((ll)(*nxt-x-1));
}
void dfs3(int x,int father,int h) {
	calc(x);
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father || y==h) continue;
		dfs3(y,x,h);
	}
}
void clr(int x,int father) {
	cnt[x]=0;
	dfn[x]=x,d[x]=1;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=father) clr(y,x);
	}
}
void dfs2(int x,int father) {
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father || y==hson[x]) continue;
		dfs2(y,x);
		clr(y,x);
		out.clear(),out.insert(0),out.insert(n+1);
		res1=0ll,res0=val((ll)n);
	}
	if(hson[x]) dfs2(hson[x],x);
	dfs3(x,father,hson[x]);
	ans+=val((ll)n)-res1-res0;
}
int main() {
    scanf("%d",&n);
    for(int x,y,i=1; i<n; i++) {
    	scanf("%d%d",&x,&y);
    	add(x,y);
    	add(y,x);
	}
	dfs1(1,0);
	for(int i=1; i<=n; i++) dfn[i]=i,d[i]=1;
	out.insert(0),out.insert(n+1);
	res1=0,res0=val((ll)n);
	dfs2(1,0);
	printf("%lld",ans);
	return 0;
}

例题:[NOIP2016 提高组] 天天爱跑步

  1. 考虑将路径 (s,t)(s,t) 拆分成 (s,lcas,t)(s,lca_{s,t}) 和 (t,lcas,t)(t,lca_{s,t}) 两条方向向父亲节点的路径,对于任意路经 (s,lcas,t)(s,lca_{s,t}) 的 ss 点产生贡献的时间均为 00 时刻,且方向向父亲节点的路径的时间是顺时,而于路径 (t,lcas,t)(t,lca_{s,t}) 的 tt 点产生贡献的时间为路径 (s,t)(s,t) 的距离,且方向向父亲节点的路径的时间是逆时

  2. 那么对于当前节点的贡献,只需要统计以当前节点 xx 为根的子树内的可以对节点 xx 产生贡献的起点和终点:

  • 对于合法的起点 ss:deps=depx+wxdep_{s}=dep_{x}+w_{x}
  • 对于合法的终点 tt:timt−(dept−depx)=wx→timt−dept=wx−depxtim_{t}-(dep_{t}-dep_{x})=w_{x} \to tim_{t}-dep_{t}=w_{x}-dep_{x}
  1. 思考任意起点 ss 对应路经 (s,lcas,t)(s,lca_{s,t}),发现对于节点 lcas,tlca_{s,t} 的父亲节点以及祖先节点,起点 ss 无法继续产生贡献,为了避免错误统计,考虑在节点 lcas,tlca_{s,t} 的父亲节点处记录对应起点 ss 的信息的删点

  2. 开桶统计所有深度的起点和终点,以及相对应的删点的数量,那么树上启发式合并维护统计以每个节点为根的子树的贡献的过程,显然保留以重儿子为根的子树的桶的信息,时间复杂度 O(nlog⁡n)O(n\log n)


Code:

C++
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mkp make_pair
#define fir first
#define sec second
const int N=6e5+10;
const int base=3e5+10;
const int TT=21;
int n,m,w[N],st[N],ed[N],ans[N];
vector<int> a[N];
vector<pair<int,int> > b[N];
struct EDGE {
	int v,lt;
}E[N*2];
int head[N],tot;
void add(int u,int v) {
	E[++tot].v=v;
	E[tot].lt=head[u];
	head[u]=tot;
}
int hson[N],siz[N],dep[N],fa[TT][N];
void dfs1(int x,int father) {
	siz[x]=1,dep[x]=dep[father]+1,fa[0][x]=father;
	for(int t=1; t<TT; t++) fa[t][x]=fa[t-1][fa[t-1][x]];
	int h=0;
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y==father) continue;
		dfs1(y,x);
		siz[x]+=siz[y];
		if(siz[y]>siz[h]) h=y;
	}
	hson[x]=h;
}
int LCA(int x,int y) {
	if(dep[x]>dep[y]) swap(x,y);
	for(int t=TT-1; t>=0; t--)
	    if(dep[fa[t][y]]>=dep[x]) y=fa[t][y];
	if(x==y) return x;
	for(int t=TT-1; t>=0; t--)
	    if(fa[t][x]!=fa[t][y]) x=fa[t][x],y=fa[t][y];
	return fa[0][x];
}
int mp[N],num;
int cnt0[N],cnt1[N],del0[N],del1[N];
void dfs3(int x,int father,int h) {
	for(auto i:a[x]) {
		if(i==0) cnt0[dep[x]]++;
		else cnt1[mp[i-dep[x]+base]]++;
	}
	for(auto i:b[x]) {
		if(i.sec==0) del0[i.fir]++;
		else del1[i.fir]++;
	}
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=father && y!=h) dfs3(y,x,h);
	}
}
void clr(int x,int father) {
	for(auto i:a[x]) {
		if(i==0) cnt0[dep[x]]--;
		else cnt1[mp[i-dep[x]+base]]--;
	}
	for(auto i:b[x]) {
		if(i.sec==0) del0[i.fir]--;
		else del1[i.fir]--;
	}
	for(int i=head[x]; i; i=E[i].lt) {
		int y=E[i].v;
		if(y!=father) clr(y,x);
	}
}
void dfs2(int x,int father) {
	for(int i=head[x]; i; i=E[i].lt) {
	    int y=E[i].v;
	    if(y==father || y==hson[x]) continue;
	    dfs2(y,x);
	    clr(y,x);
	}
	if(hson[x]) dfs2(hson[x],x);
	dfs3(x,father,hson[x]);
	ans[x]+=cnt0[dep[x]+w[x]]-del0[dep[x]+w[x]];
	// 对终点的合法要求: now[i]-(dep[i]-dep[x])=w[x] -> now[i]-dep[i]=w[x]-dep[x]
 	if(mp[w[x]-dep[x]+base])
		ans[x]+=cnt1[mp[w[x]-dep[x]+base]]-del1[mp[w[x]-dep[x]+base]];
}
int main() {
    scanf("%d%d",&n,&m);
    for(int x,y,i=1; i<n; i++) {
    	scanf("%d%d",&x,&y);
    	add(x,y);
    	add(y,x);
	}
	for(int i=1; i<=n; i++) scanf("%d",&w[i]);
	for(int i=1; i<=m; i++)
		scanf("%d%d",&st[i],&ed[i]);
	dfs1(1,0);
	for(int i=1; i<=m; i++) {
		int lca=LCA(st[i],ed[i]);
		int tim=dep[st[i]]+dep[ed[i]]-dep[lca]*2;
		a[st[i]].pb(0);
		b[fa[0][lca]].pb(mkp(dep[st[i]],0));
		if(ed[i]!=lca) { // 考虑将路径 st->ed 拆分成 st->lca,ed->lca 两条路经
			a[ed[i]].pb(tim); // 统计以节点 x 根的子树内可以产生贡献的起点和终点
			if(!mp[tim-dep[ed[i]]+base]) mp[tim-dep[ed[i]]+base]=++num;
			b[lca].pb(mkp(mp[tim-dep[ed[i]]+base],1));
		}
	}
	dfs2(1,0);
	for(int i=1; i<=n; i++) printf("%d ",ans[i]);
	return 0;
}

原文