Today, the efficiency is good, learned a lot of things, of which there are and check set, of course, I only learned a small part, but also need to do more to consolidate and practice.
#include <iostream>using namespacestd;classDisjointset {Private: int*father, *rank; Public: Disjointset (intsize) {Father=New int[size]; Rank=New int[size]; for(inti =0; i < size; ++i) {Father[i]=i; Rank[i]=0; } } ~Disjointset () {Delete[] Father; Delete[] rank; } //Finding root Nodes intFind_set (intnode) { if(Father[node]! =node) {Father[node]= Find_set (Father[node]);//Path Compression Optimization } returnFather[node]; } //Merging root nodes BOOLMergeintNode1,intNode2) { intAncestor1 =Find_set (Node1); intAncestor2 =Find_set (Node2); if(Ancestor1! =Ancestor2) { if(Rank[ancestor1] >Rank[ancestor2]) {Swap (Ancestor1, ANCESTOR2); } Father[ancestor1]=Ancestor2; Rank[ancestor2]= Max (Rank[ancestor1] +1, Rank[ancestor2]);//Consolidation by rank optimization return true; } return false; }};intMain () {Disjointset DSU ( -); intm, x, y; CIN>>m; for(inti =0; I < m; ++i) {cin>> x >>y; BOOLAns =dsu.merge (x, y); if(ans) {cout<<"Success"<<Endl; } Else{cout<<"failed"<<Endl; } } return 0;}
and check Set