- 一、引言
- 二、C++实现
- 三、测试
二、C++实现并查集的相关介绍
#include三、测试using namespace std; class Ufset { private: int* parent; size_t size; //parent对象的个数 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;
}



