一、引言
并查集的相关介绍
二、C++实现
#include<iostream>
using namespace std;
class Ufset
{
private:
int* parent;
size_t size;
private:
void Showchild(int child)const
{
cout << child << " ";
for (int i = 0; i < size; ++i)
{
if (child == parent[i])
{
Showchild(i);
}
}
}
public:
Ufset(int sz) :parent(new int[sz]), size(sz)
{
for (int i = 0; i < size; ++i)
{
parent[i] = -1;
}
}
~Ufset()
{
if (nullptr != parent)
{
delete[] parent;
size = 0;
}
}
int FindRoot(int child)const
{
while (parent[child] >= 0)
{
child = parent[child];
}
return child;
}
bool Union(int cha, int chb)
{
bool res = false;
int left = FindRoot(cha);
int right = FindRoot(chb);
if (left != right)
{
parent[left] += parent[right];
parent[right] = left;
res = true;
}
return true;
}
void ShowAllSet()const
{
int si = 1;
for (int i = 0; i < size; ++i)
{
if (parent[i] < 0)
{
cout << "set" << si++ << ": ";
Showchild(i);
cout << endl;
}
}
}
};
三、测试
int main()
{
Ufset s(12);
s.Union(0, 4);
s.Union(3, 1);
s.Union(6, 10);
s.Union(8, 9);
s.Union(7, 4);
s.Union(6, 8);
s.Union(3, 5);
s.Union(2, 11);
s.Union(11, 0);
s.ShowAllSet();
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e0a6890613c0b760d9ed4e2ac229af75.png)