一、并查集原理
在一些应用问题中,需要将n个不同的元素划分成一些不相交的集合。开始时,每个元素自成一个单元素集合,然后按一定的规律将归于同一组元素的集合合并。在此过程中要反复用到查询某一个元素归属于那个集合的运算。适合于描述这类问题的抽象数据类型称为并查集(unionfindset)。
比如:某公司今年校招全国总共招生10人,西安招4人,成都招3人,武汉招3人,10个人来自不
同的学校,起先互不相识,每个学生都是一个独立的小团体,现给这些学生进行编号:{0, 1, 2, 3,4, 5, 6, 7, 8, 9}; 给以下数组用来存储该小集体,数组中的数字代表:该小集体中具有成员的个
数。(负号下文解释)
毕业后,学生们要去公司上班,每个地方的学生自发组织成小分队一起上路,于是:
西安学生小分队s1={0,6,7,8},成都学生小分队s2={1,4,9},武汉学生小分队s3={2,3,5}就相互认识
了,10个人形成了三个小团体。假设右三个群主0,1,2担任队长,负责大家的出行。
从上图可以看出:编号6,7,8同学属于0号小分队,该小分队中有4人(包含队长0);编号为4和9的同学属于1号小分队,该小分队有3人(包含队长1),编号为3和5的同学属于2号小分队,该小分队有3个人(包含队长1)。
仔细观察数组中内融化,可以得出以下结论:
- 数组的下标对应集合中元素的编号
- 数组中如果为负数,负号代表根,数字代表该集合中元素个数
- 数组中如果为非负数,代表该元素双亲在数组中的下标
在公司工作一段时间后,西安小分队中8号同学与成都小分队1号同学奇迹般的走到了一起,两个
小圈子的学生相互介绍,最后成为了一个小圈子:
现在0集合有7个人,2集合有3个人,总共两个朋友圈。
通过以上例子可知,并查集一般可以解决一下问题:
- 查找元素属于哪个集合
沿着数组表示树形关系以上一直找到根(即:树中中元素为负数的位置) - 查看两个元素是否属于同一个集合
沿着数组表示的树形关系往上一直找到树的根,如果根相同表明在同一个集合,否则不在 - 将两个集合归并成一个集合
将两个集合中的元素合并
将一个集合名称改成另一个集合的名称 - 集合的个数
遍历数组,数组中元素为负数的个数即为集合的个数。
二、 并查集实现
class UnionFindSet
{
private:
std::vector<int> _a;
public:
// 初始时,将数组中元素全部设置为1
UnionFindSet(size_t n)
{
_a.resize(n, -1);
}
~UnionFindSet()
{
}
public:
// 给一个元素的编号,找到该元素所在集合的名称
int FindRoot(size_t index)
{
int root = index;
while (_a[root] >= 0)
{
root = _a[root];
}
// 路径压缩
while (_a[index] >= 0)
{
int parent = _a[index];
_a[index] = root;
index = parent;
}
return root;
}
// 将两个集合中元素合并
bool Union(int x1, int x2)
{
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
// 在同一集合,查找失败!
if (root1 == root2)
return false;
if (abs(_a[root1]) < abs(_a[root2]))
std::swap(root1, root2);
// 进行合并
_a[root1] += _a[root2];
_a[root2] = root1;
return true;
}
// 数组中负数的个数,即为集合的个数
size_t Count() const
{
int count = 0;
for (size_t i = 0; i < _a.size(); ++i)
{
if (_a[i] < 0)
{
++count;
}
}
return count;
}
};
三、并查集应用
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
vector<int> ufs(isConnected.size(), -1);
auto FindRoot = [&ufs](int index){
while(ufs[index] >= 0)
{
index = ufs[index];
}
return index;
};
for(int i = 0; i < isConnected.size(); ++i)
{
for(int j = 0; j < i; ++j)
{
if(isConnected[i][j] == 1)
{
int root1 = FindRoot(i);
int root2 = FindRoot(j);
if(root1 != root2)
{
ufs[root1] += ufs[root2];
ufs[root2] = root1;
}
}
}
}
int count = 0;
for(auto e : ufs)
{
if(e < 0)
{
++count;
}
}
return count;
}
};
class Solution {
public:
bool equationsPossible(vector<string>& equations) {
vector<int> ufs(26, -1);
auto FindRoot = [&ufs](int index){
while(ufs[index] >= 0)
{
index = ufs[index];
}
return index;
};
for(auto& eq : equations)
{
if(eq[1] == '=')
{
int root1 = FindRoot(eq[0]-'a');
int root2 = FindRoot(eq[3]-'a');
if(root1 != root2)
{
ufs[root1] += ufs[root2];
ufs[root2] = root1;
}
}
}
for(auto& eq : equations)
{
if(eq[1] == '!')
{
int root1 = FindRoot(eq[0]-'a');
int root2 = FindRoot(eq[3]-'a');
if(root1 == root2)
{
return false;
}
}
}
return true;
}
};