跳到正文

算法·理论

并查集

AC_Snake约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年3月30日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 5 分钟

版本

  1. v1当前

并查集 (Union-Find Set)

定义:是一种树形结构,用于合并两个集合,以及查找某一个元素x在那个集合里。

实现步骤:

  1. 预处理每个元素的初始点,fa[i]=i;

  2. 设计查询函数find(x)返回x所在树的根节点编号:

C++
int find(int x){
    if(x==f[x])    return x;
    return find(f[x]);
}
  1. 设计合并函数union(x,y)将x和y所在的树合并成一棵树:
C++
void unionn(int x,int y){
	x=find(x),y=find(y);
	if(x!=y)	f[x]=y;
	return;
} 

时间复杂度:

说明:朴素的并查集时间复杂度取决于find()函数,而find()取决于树的高度,而树的高度至多为n,因此单次调用的时间复杂度为O(n)。

无优化:O(mn);

优化:

  1. 路径压缩:当执行find()时,将x以及x的祖先节点都直接连向root,那么之后再遇到这些点时,就可以O(1)查询了。
C++
int find(int x){
    if(x==f[x])    return x;
    return f[x]=find(f[x]);
}
  1. 按秩合并:两棵树合并时,总是用小的树向大的树合并即可。

并查集的基础应用:

  1. 合并和查询:

    • 例题:P3367 【模板】并查集

    • 代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"

int const N=2e5+10;
int n,m,f[N];

int find(int x){
	if(x==f[x])	return x;
	return f[x]=find(f[x]);
}

void unionn(int x,int y){
	x=find(x),y=find(y);
	if(x!=y)	f[x]=y;
	return;
}

signed main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++)	f[i]=i;
	while(m--){
		int z,x,y;
		cin>>z>>x>>y;
		if(z==2){
			if(find(x)==find(y)){
				cout<<"Y\n";
			}
			else{
				cout<<"N\n";
			}
		}
		if(z==1)	unionn(x,y);
	}
	return 0;
} 

并查集的进阶应用:

  1. 判断连通性,连通可以转化为对于是否在一个集合的判断。
    • 例题:P1551 亲戚
    • 代码:
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"

int const N=1e6+10;
int n,m,p,f[N];

int find(int x){
	if(x==f[x])	return x;
	return f[x]=find(f[x]);
}

void unionn(int x,int y){
	x=find(x),y=find(y);
	if(x!=y)	f[x]=y;
	return;
}

signed main(){
	cin>>n>>m>>p;
	for(int i=1;i<=n;i++)	f[i]=i;	
	for(int i=1;i<=m;i++){
		int x,y;
		cin>>x>>y;
		unionn(x,y); 
	}
	for(int i=1;i<=p;i++){
		int p1,p2;
		cin>>p1>>p2;
		if(find(p1)==find(p2))	cout<<"Yes\n";
		else	cout<<"No\n";
	}
	return 0;
}
  1. 判断是否成环,对于一条边连边(a,b),若连边前a和b已经在同一棵树中,则连边后一定成环。
    • 例题:P2307 迷宫
    • 代码:
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"

int const N=1e5+10;
int f[N],an[N],top;
bool win;

int find(int x){
	if(f[x]==x)	return x;
	return f[x]=find(f[x]);
}

void unionn(int x,int y){
	x=find(x),y=find(y);
	if(x!=y)	f[x]=y;
	return;
}

signed main(){
	while(true){
		int x,y;
		memset(f,0,sizeof(f));
		memset(an,0,sizeof(an));
		win=1,top=0;
		while(cin>>x>>y){
			if(x==-1 && y==-1)	return 0;
			if(x==0 && y==0)	break;
			if(!f[x])	f[x]=x,an[++top]=x;
			if(find(x)==find(y))	win=0;
			else{
				if(!f[y])	f[y]=y,an[++top]=y;
				unionn(x,y);
			}
		}
		if(win){
			int res=0;
			for(int i=1;i<=top;i++){
				if(f[an[i]]==an[i])	res++;
			}
			if(res!=1)	cout<<0<<endl;
			else	cout<<1<<endl;
		}
		else	cout<<0<<endl;
	}
	return 0;
}
原文