并查集
概念
并查集是一种简单的集合表示,支持2种操作:
- 查找集合S中元素x所在子集合,并返回子集合名字。
- 把集合S中子集合root2并入子集合root1,要求2集合互不相交。
通常用森林的双亲作为并查集的存储结构,每个集合以一棵树表示。
模板
#include <iostream>
#include <vector>
using namespace std;
typedef int ElementType;
struct Set
{
ElementType data;
int parent;
};
// 查找某个元素所在集合(用根结点表示)
int Find(vector<Set> &S, ElementType x)
{
int i;
for (i = 0; i < S.size() && S[i].data != x; i++)
{
;
}
if (i >= S.size())
{
return -1;
}
for (; S[i].parent >= 0; i = S[i].parent)
{
;
}
return i;
}
// 集合并操作
void Union(vector<Set> &S, ElementType x1, ElementType x2)
{
int root1, root2;
root1 = Find(S, x1);
root2 = Find(S, x2);
if (root1 != root2)
{
S[root2].parent = root1;
}
}
int main()
{
vector<Set> S(10);
// Parent
// -1 0 -1 0 2 -1 0 2 5 5
for (int i = 0; i < 10; i++)
{
S[i].data = i + 1;
int tmp;
cin >> tmp;
S[i].parent = tmp;
}
Union(S, 10, 5);
for (auto it : S)
{
cout << it.data << " " << it.parent << endl;
}
system("pause");
return 0;
}