跳到正文

算法·理论

可持久化并查集

用户 836345约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月8日
篇幅
约 5 分钟

版本

  1. v1当前

可持久化并查集

基于可持久化线段树,模板题

主要依靠可持久化线段树的结构记录每一版并查集的秩(fa),在可持久化线段树的这种应用中,刻画实际并查集信息的只有叶子节点,其他非叶节点的作用主要体现在连接新旧版本,以避免重复信息对空间的占用。

比较妙的一点在于,在这棵可持久化线段树中,编号范围在 1→tot1\to tot 的叶节点的 fa 却 ∈(1,n)\in(1,n),这正是在新版本中旧版本蕴含的信息得以延续的关键,因为这个信息并不针对某个版本的某个点,而是针对在此之后所有版本的某个点。

所以,每次执行合并操作时,我们先是需要外层的 O(logn)O(logn) 的复杂度一步步找到二者的 fa,然后内层还需要 O(logn)O(logn) 的复杂度 query 出 fa 在以 root[now] 为根的版本的线段树中对应的叶节点编号。

其中,并查集并的方式我们选择只按秩合并(显然没法路径压缩),可以用 dep 或 siz 来定义秩。对于需要更改秩的一方(dep/siz 更小),新开 logn 的点数来记录,当 dep/siz 大的一方的 dep/siz 因为新成员的加入而需要更改时,也需要新开点数(所以这里用 dep 常数更小)。

总结一下,时间复杂度 O(mlog2n)O(mlog^2n),空间复杂度 O(4n+2mlogn)O(4n+2mlogn)。

C++
#include<bits/stdc++.h>
using namespace std;
const int Maxn=1e5;
int n,m;
struct Node
{
	int ls,rs;
	int fa,dep;
}tr[Maxn<<6];
int tot,root[Maxn*2+5];
int build(int l,int r)
{
	int now=++tot;
	if (l==r)
    {
    	tr[now].fa=l;
    	tr[now].dep=1;
    	return now;
	}
	int mid=(l+r)/2;
	tr[now].ls=build(l,mid);
	tr[now].rs=build(mid+1,r);
	return now;
}
int query(int now,int l,int r,int pos)
{
	if (l==r)
	    return now;
	int mid=(l+r)/2;
	if (pos<=mid)
	    return query(tr[now].ls,l,mid,pos);
	return query(tr[now].rs,mid+1,r,pos);
}
int upd(int pre,int l,int r,int pos,int f)
{
	int now=++tot;
	if (l==r)
	{
		tr[now].fa=f;
		return now;
	}
	int mid=(l+r)/2;
	if (pos<=mid)
	{
		tr[now].rs=tr[pre].rs;
		tr[now].ls=upd(tr[pre].ls,l,mid,pos,f);
	}
	else
	{
		tr[now].ls=tr[pre].ls;
		tr[now].rs=upd(tr[pre].rs,mid+1,r,pos,f);
	}
	return now;
}
int add(int pre,int l,int r,int pos)
{
	int now=++tot;
	if (l==r)
	{
		tr[now].fa=l;//**
		tr[now].dep=tr[pre].dep+1;
		return now;
	}
	int mid=(l+r)/2;
	if (pos<=mid)
	{
		tr[now].rs=tr[pre].rs;
		tr[now].ls=add(tr[pre].ls,l,mid,pos);
	}
	else
	{
		tr[now].ls=tr[pre].ls;
		tr[now].rs=add(tr[pre].rs,mid+1,r,pos);
	}
	return now;
}
int find(int ver,int pos)
{
	int nod=query(root[ver],1,n,pos);
	if (tr[nod].fa==pos)
	    return pos;
	return find(ver,tr[nod].fa);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>m;
    root[0]=build(1,n);
    for (int i=1;i<=m;i++)
    {
    	int op,x,y;
    	cin>>op;
    	if (op==1)
    	{
    		cin>>x>>y;
    		x=find(i-1,x);
    		y=find(i-1,y);
    		if (x==y)
    		{
    			root[i]=root[i-1];
    			continue;
			}
			int nodx=query(root[i-1],1,n,x);
			int nody=query(root[i-1],1,n,y);
			if (tr[nodx].dep>tr[nody].dep)
			{
				swap(nodx,nody);
				swap(x,y);
			}
			root[i]=upd(root[i-1],1,n,x,y);
			if (tr[nodx].dep==tr[nody].dep)
			    root[i]=add(root[i],1,n,y);
		}
		else if (op==2)
		{
			cin>>x;
			root[i]=root[x];
		}
		else
		{
			cin>>x>>y;
			root[i]=root[i-1];
			if (find(i,x)==find(i,y))
			    cout<<"1\n";
			else
			    cout<<"0\n";
		}
	}
	return 0;
}
原文