跳到正文

个人记录

2025.11.23知识要点+题目解析+总结

xiangrui0305约 3 分钟
原文

这是 2025年11月29日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

总结需要一个头图:

2025.11.23知识要点+题目解析+总结

知识要点:并查集

一、并查集概念讲解
集合是数学中的基本结构,表示一组互不相同的元素。在并查集中,我们会管理多个“不相交”的集合,并对集合进行一些操作。“不相交”指任意两个集合没有相同的因素。

二、基本操作及代码实现
1、一般用集合中的一个元素表示这个集合中的“老板”。
2、一开始每个元素都有自己的集合,在自己的集合里只有这个元素自己,即每个元素都是老板。

C++
int p[N];
for(int i=1;i<=n;++i) p[i] = 1;

3、查找xx所在集合的老板,用老板代表xx所在的集合。

C++
int find(int x){
	if(p[x] == x) return x;
	return p[x] = find(p[x]);
}

经过若干次find之后,有可能所有的员工的直接领导都是老板。
4、判断 aa 和 bb 这 22 个元素是否在一个集合里。

C++
if(find(x) == find(y)) cout<<"Yes\n";
else cout<<"No\n";

5、将 aa 所在集合的所有元素与 bb 所在集合所有元素合并形成一个集合。

C++
void merge(int a,int b){
	int t1 = find(a),t2 = find(b);
	if(t1 != t2) p[t2] = t1;
}

6、如何判断一共有多少个集合?
判断多少个集合就是判断有多少个老板。

C++
int cnt = 0;
for(int i=1;i<=n;++i){
    if(p[i] == i) cnt++;
}

题目解析+总结

P3367【模板】并查集

分析题干+步骤书写

参考知识要点,具体看代码注释。

AC代码
C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,p[200005];
int find(int x){ //查找操作
	if(p[x] == x) return x;
	return p[x] = find(p[x]);
}
void merge(int a,int b){ //合并操作
	int t1 = find(a),t2 = find(b); //为了不浪费时间,先用变量存储起来
	if(t1 != t2) p[t2] = t1;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;++i) p[i] = i;
	while(m--){
		int z,x,y;
		cin>>z>>x>>y;
		if(z == 1) merge(x,y);
		if(z == 2){
			if(find(x) == find(y)) cout<<"Y\n";
			else cout<<"N\n";
		}
	}
	return 0;
}