UnionSet —— 并查集
什么是并查集?并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。一些常见的用途有求连通子图、求最小生成树的 Kruskal 算法和求最近公共祖先(Least Common Ancestors, LCA)等。
并查集的主要操作:
1、初始化:把每个点所在集合初始化为其自身;
2、查找:查找元素所在的集合即根节点;
3、合并:将两个元素所在的集合合并为一个集合,合并两个不相交集合判断两个元素是否属于同一集合。
class UnionSet
{
public:
UnionSet(int n)
{
_a.resize(n, -1);
}
int FindRoot(int x)
{
int root = x;
if (_a[root] >= 0)
{
root = _a[root];
}
return root;
}
void Union(int x1, int x2)
{
int root1 = FindRoot(x1);
int root2 = FindRoot(x2);
if (root1 != root2)
{
_a[root1] += _a[root2];
_a[root2] = root1;
}
}
int GetSet()
{
int count = 0;
for (size_t i = 0; i < _a.size(); i++)
{
if (_a[i] < 0)
{
count++;
}
}
return count;
}
protected:
vector<int> _a;
};
例:假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友…),则认为他们属于同一个朋友圈。请写程序求出这n个人里一共有多少个朋友圈。
如:n = 5,m = 3, r = {{1,2}, {2,3}, {4,5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈。结果为两个朋友圈。
int friends(int n, int m, int r[][2])
{
assert(r);
UnionSet u(n + 1);//多开一个空间,0号位置不用
for (int i = 0; i < m; i++)
{
int r1 = r[i][0];
int r2 = r[i][1];
u.Union(r1, r2);
}
return u.GetSet() - 1;//因为0号位置没有用,但初始化时为-1,就会多一个负数,所以减去1
}
void Test1()
{
int r[4][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }};//n=总人数,m=多少对好友关系
cout << friends(5, 3, r) << "个朋友圈" << endl;
}