并查集支持查找以下操作:
1、合并:合并两个集合;
2、查找:判断两个元素是否在同一个集合中。其核心是用一个数组实现。
#include <iostream>
#include <set>
using namespace std;
const int MAX = 10;
int father[MAX];//并查集,father[i]表示元素i的父结点
bool flag[MAX] = {false};
int count = 0;
void initUFS() { //初始化
for (int i = 1; i <= MAX; ++i) {
father[i] = i;
}
}
int findFather(int x) {//查找元素x所在集合的根结点,递推写法
while (x != father[x]) {
x = father[x];
}
return x;
}
int findFather1(int x) {//查找元素x所在集合的根结点,递归写法
if (x == father[x]) return x;
else return findFather1(father[x]);
}
void Union(int a, int b) {//合并a和b所在的集合
int fatherA = findFather(a);
int fatherB = findFather(b);
if (fatherA != fatherB)
father[fatherA] = fatherB;
}
int BestfindFather(int x) { //查找根结点优化,路径压缩,将从x开始查到根结点的路径所经过的所有结点的父结点都置为根结点
int a = x;
while (x != father[x]) {
x = father[x];
}
while (a != father[a]) {
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
int main() {
set<int> s;
int n, m;
cin >> n >> m;
initUFS();
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
Union(a, b);
}
for (int j = 1; j <= n; ++j) {
s.insert(findFather(j));
}
cout << s.size();
return 0;
}