一、原理
并查集:
1.将两个集合合并;
2.询问两个元素是否在一个集合中。
基本原理:每个集合用一棵树来表示,树根的编号就是整个集合的编号,每个节点存储它的父节点,p[x]表示 x 的父节点。
优化:路径压缩。
问题一:如何判断树根:if(p[x] == x)
问题二:如何求x的集合编号:while(p[x] != x) x = p[x];
问题三:如何合并两个集合:px是x的集合编号,py是y的集合编号。p[x] = y。
二、代码
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int N = 100010;
int n, m;
int p[N];
int find(int x){ // 返回 x 的祖宗节点 + 路径压缩
if(p[x] != x)
p[x] = find(p[x]);
return p[x];
}
int main(){
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
p[i] = i;
while(m--){
char op[2]; //scanf读入字符时不会忽略空格,读入字符串时会忽略空格。
int a, b;
scanf("%s%d%d", op, &a, &b);
if(op[0] == 'M')
p[find(a)] = find(b);
else{
if(find(a) == find(b))
puts("Yes");
else
puts("No");
}
}
}