跳到正文

算法·理论

并查集

Zhou_Lemon约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年8月8日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 2 分钟

版本

  1. v1当前

并查集概念

一种可供合并集合、查询连通性、分裂(不常见)的数据结构。

并查集模版

C++
struct BCJ{
	int f[N];  bool same[N];
	inline void clear(int x){//初始化
		for(int i=1;i<=x;i++)f[i]=i;
	}
	inline int find(int x){//查询
        return (f[x]==x) ? x : f[x]=find(f[x]);
    }
	inline void Union(int x,int y,bool b){//合并
		if(find(x)!=find(y))
            f[find(x)]=find(y);
	}
}g;

注意:
若有分裂的题目,则不可路径压缩。

带权并查集

这里要处理好路径压缩时 xx 与 f[x]f[x] 与 find(f[x])find(f[x]) 的权值关系。
模板:

C++
struct BCJ{
	int f[N];  bool same[N];
	inline void clear(int x){
		for(int i=1;i<=x;i++)
			f[i]=i,same[i]=0;//0->相同    1->不同 
	}
	inline int find(int x){
		if(f[x]==x)return x;
		int fa=f[x]; f[x]=find(f[x]);
		same[x]^=same[fa]^same[f[x]];
		return f[x];
	}
	inline void Union(int x,int y,bool b){
		int fx=find(x),fy=find(y);
		if(fx==fy)return;  f[fx]=fy;
		if(b&&same[x]!=same[y])same[fx]=1;
		if(!b&&same[x]==same[y])same[fx]=1;
	}
}g;

扩展域并查集

用于处理集合之间的相对关系,一般都可以用带权并查集替代。

并查集应用

在图论中一般用于维护点集的连通性(当然也可以维护序列),即维护一个动态无向图的联通块。其合并操作可与其他数据结构配合,如线段树合并。
并查集是一种树形数据结构,其路径压缩在树中有很大用处,如求 LCALCA 的 TarjanTarjan 算法。

并查集题目

银河英雄传说
[COCI 2013/2014 #5] LADICE

原文