2025.11.23知识要点+题目解析+总结
知识要点:并查集
一、并查集概念讲解 集合是数学中的基本结构,表示一组互不相同的元素。在并查集中,我们会管理多个“不相交”的集合,并对集合进行一些操作。“不相交”指任意两个集合没有相同的因素。
二、基本操作及代码实现 1、一般用集合中的一个元素表示这个集合中的“老板”。 2、一开始每个元素都有自己的集合,在自己的集合里只有这个元素自己,即每个元素都是老板。
int p[N];
for(int i=1;i<=n;++i) p[i] = 1;3、查找所在集合的老板,用老板代表所在的集合。
int find(int x){
if(p[x] == x) return x;
return p[x] = find(p[x]);
}经过若干次find之后,有可能所有的员工的直接领导都是老板。 4、判断 和 这 个元素是否在一个集合里。
if(find(x) == find(y)) cout<<"Yes\n";
else cout<<"No\n";5、将 所在集合的所有元素与 所在集合所有元素合并形成一个集合。
void merge(int a,int b){
int t1 = find(a),t2 = find(b);
if(t1 != t2) p[t2] = t1;
}6、如何判断一共有多少个集合? 判断多少个集合就是判断有多少个老板。
int cnt = 0;
for(int i=1;i<=n;++i){
if(p[i] == i) cnt++;
}题目解析+总结
P3367【模板】并查集
分析题干+步骤书写
参考知识要点,具体看代码注释。
AC代码
#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;
}