#include <iostream>
#include <vector>
using namespace std;
//并查集
class UnionFindSet{
public:
UnionFindSet(size_t n){
_ufs.resize(n,-1);
}
int FindRoot(int x){
while(_ufs[x] >= 0){ //不是根
x = _ufs[x];
}
return x; //是根
}
//并查集的合并
void Unoin(int x1,int x2){
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
//根合并
if(root1 != root2){ //不是一个集合
_ufs[root1] += _ufs[root2];
_ufs[root2] = root1;
}
}
size_t Size(){ //有几个集合
size_t n = 0;
for(auto e : _ufs){
if(e < 0)
++n;
}
return n;
}
private:
vector<int> _ufs;
};
C++实现简单的 并查集
最新推荐文章于 2024-05-11 15:27:33 发布