并查集原理
在一些应用问题中,需要将n个不同的元素划分成一些不相交的集合。开始时,每个元素自成一个单元素集合,然后按一定的规律将归于同一组元素的集合合并。在此过程中要反复用到查询某一个元素归属于那个集合的运算。适合于描述这类问题的抽象数据类型称为并查集(union-find set)。
例如:省份数量
1.初始化数组将所有的元素初始化为-1,数组下标对应对象的编号
如果要用下图表示对应的集合关系
仔细观察数组中内融化,可以得出以下结论:
-
数组的下标对应集合中元素的编号
-
数组中如果为负数,负号代表根,数字代表该集合中元素个数
-
数组中如果为非负数,代表该元素双亲在数组中的下标
并查集实现
class unionFindSet
{
public:
unionFindSet(size_t n)
:_ufs(n,-1)
{}
void gather(int x1,int x2)
{
int root1 = findRoot(x1);
int root2 = findRoot(x2);
if (root1 == root2)
{
return;
}
// 不为同一个集
// 优化,将并查集小的树,放在大的树下面
if (_ufs[root1] > _ufs[root2])
{
swap(root1, root2);
}
_ufs[root1] += _ufs[root2];
_ufs[root2] = root1;
}
int findRoot(int x)
{
int root = x;
//找为负数的下标 根
while (_ufs[root] >= 0)
{
root = _ufs[root];
}
return root;
}
bool isSameRoot(int x1, int x2)
{
int root1 = findRoot(x1);
int root2 = findRoot(x2);
return root1 == root2;
}
private:
vector<int> _ufs;
};