原题链接:
https://www.acwing.com/problem/content/838/https://www.acwing.com/problem/content/838/思路:
首先建立一个p[x]数组,来表示x的根节点;
一开始所有的数的根节点是它本身,所以先初始化一遍p[i]=i;
查集的最关键的操作就是查找x的根节点;
int find (int x) // 返回x的根节点+路径压缩
{
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
并集的关键就是让a的根节点接在b上,或者让b的根节点接在a上;
p[find(a)]=p[find(b)];//统一a,b的根节点
由此结束;
判断两个数是否在一个集合里面只需要判断它们的根节点是否相同即可;
代码:
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int p[N];
int n,m;
int find (int x) // 返回x的根节点+路径压缩
{
if(p[x]!=x) p[x]=find(p[x]);
return p[x];
}
int main ()
{
cin >> n >> m;
for(int i=1;i<=n;i++){
p[i]=i;
}
while(m--){
char op[2];
int a,b;
cin >> op;
cin >> a >> b;
if(op[0]=='M')
p[find(a)]=p[find(b)];//统一a,b的根节点
if(op[0]=='Q')
if(find(a)==find(b))
cout <<"YES" << "\n";
else cout << "NO" << "\n";
}
return 0;
}