标签:并查集
在一些有N个元素的集合应用问题中,我们通常是在开始时让每个元素构成一个单元素的集合,然后按一定顺序将属于同一组的元素所在的集合合并,其间要反复查找一个元素在哪个集合中。
动态连通性一类问题的一种算法,使用到了一种叫做并查集的数据结构,称为Union-Find。
建模思路:
最简单而直观的假设是,对于连通的所有节点,我们可以认为它们属于一个组,因此不连通的节点必然就属于不同的组。随着Pair的输入,我们需要首先判断输入的两个节点是否连通。如何判断呢?按照上面的假设,我们可以通过判断它们属于的组,然后看看这两个组是否相同,如果相同,那么这两个节点连通,反之不连通。为简单起见,我们将所有的节点以整数表示,即对N个节点使用0到N-1的整数表示。而在处理输入的Pair之前,每个节点必然都是孤立的,即他们分属于不同的组,可以使用数组来表示这一层关系,数组的index是节点的整数表示,而相应的值就是该节点的组号了。该数组可以初始化为:
应用:求朋友圈
#include<iostream>
using namespace std;
template<class T>
class UnionFindSets
{
public:
UnionFindSets(T* arr, size_t size)
:_size(size)
, _corspend(new T[size])
{
for (int i = 0; i < size; ++i)
{
_corspend[i] = arr[i];
}
_unionSet = new int[size];
for (int j = 0; j < size; ++j)
{
_unionSet[j] = -1;
}
}
int FindRoot(size_t index)
{
while (_unionSet[index]>= 0)
{
index = _unionSet[index];
}
return index;
}
void Union(size_t index1, size_t index2)
{
int root1 = FindRoot(index1-1);
int root2 = FindRoot(index2-1);
if (root1 != root2)
{
_unionSet[root1] += _unionSet[root2];
_unionSet[root2] = root1;
}
}
int UnionNum()
{
int count = 0;
for (int i = 0; i < _size; ++i)
{
if (_unionSet[i] < 0)
{
++count;
}
}
return count;
}
protected:
T* _corspend;// corresponding下标和键值的对应关系
int* _unionSet;
size_t _size;
};
void Test1()
{
int city[] = { 1,2,3,4,5 };
UnionFindSets<int> u(city, sizeof(city) / sizeof(city[0]));
u.Union(1, 2);
u.Union(2, 3);
u.Union(4, 5);
cout << u.UnionNum() << endl;
}
int main()
{
Test1();
system("pause");
return 0;
}本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1835812
标签:并查集
原文地址:http://10541556.blog.51cto.com/10531556/1835812