In order to introduce the graph theory algorithm in the future, here are several implementations of the union algorithm. However, this implementation is not general, but here is just to make some foreshadowing later.
#include<iostream>#include<cassert>#include<ctime>usingnamespace std;classUnionFind{private:int* id;int count;public:UnionFind(int n){
count = n;
id =newint[n];for(int i =0; i < n; i++){
id[i]= i;}}~UnionFind(){delete[] id;}intfind(int p){assert( p >=0&&p<count);return id[p];}boolisConnected(int p,int q){returnfind(p)==find(q);}voidunionElements(int p,int q){int pID =find(p);int qID =find(q);if(pID == qID){return;}for(int i =0; i < count; i++){if(id[i]== pID){
id[i]= qID;}}}};voidtestUF01(int n){srand(time(NULL));
UnionFind uf =UnionFind(n);for(int i =0; i < n; i++){int a =rand()% n;int b =rand()% n;
uf.unionElements(a, b);}for(int i =0; i < n; i++){int a =rand()% n;int b =rand()% n;
cout << a <<"\t"<< b <<"\t"<< uf.isConnected(a, b)<< endl;;}}intmain(){testUF01(100);system("pause");return0;}