并查集
普通并查集
注意根据数据大小来开int 或者 long long 否则容易MLE
树的存储结构 双亲表示法------数组 孩子表示法 孩子兄弟表示法
C++
#include <bits/stdc++.h>
using ll=long long;
using namespace std;
const int N=2e5+5;
int fa[N];
int n,m;
int find(int x){
if(x==fa[x])
return x;
else return fa[x]=find(fa[x]);
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;++i){
fa[i]=i;
}
for(int i=0;i<m;++i){
int z,x,y;cin>>z>>x>>y;
if(z==1){
//合并
int fx=find(x);
int fy=find(y);
fa[fx]=fy;
}else{
//查询
int fx=find(x);
int fy=find(y);
if(fx==fy) cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
return 0;
}
种类并查集
扩展域并查集 可描述敌对关系
敌人 朋友 没关系 扩展为2n
天敌 同类 猎物 没关系 扩展为3n
P1525 [NOIP 2010 提高组\] 关押罪犯 - 洛谷](https://www.luogu.com.cn/problem/P1525)
```C++
#include