一、引言并查集的相关介绍二、C++实现1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#include<iostream>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; } } }};三、测试12345678910111213141516//测试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;}