I. Question
II, Code
/* Unionfindset. h. Check the set. Non-recursive method, including path compression. The array starts from 0 */# include <iostream> using namespace STD; # define maxn 30005 class UFS {public: int N; int P [maxn + 1]; // set the root node int rank [maxn + 1]; // Number of vertices in the Set int depth [maxn + 1]; public: ufs (INT size = maxn); void clear (); int find_set (int x); // A is incorporated into B without distinguishing the size of void Union (INT X, int y ); void make_set (int x); void Link (int x, int y); void graft (int r, int v) ;}; UFS: UFS (INT size ): N (size) {// It must start from 0 (INT I = 0; I <= N; I ++) make_set (I);} void UFS: make_set (INT X) {P [x] = X; rank [x] = 0; depth [x] = 0;} void UFS: clear () {for (INT I = 0; I <= N; I ++) make_set (I);} int UFS: find_set (INT X) {int temp = x, sum = 0, ans; while (temp! = P [temp]) {sum = sum + depth [temp]; temp = P [temp];} ans = temp; while (X! = Ans) {sum-= depth [X]; depth [x] + = sum; temp = P [X]; P [x] = ans; X = temp ;} return ans;} void UFS: Union (int x, int y) {If (x = y) return; Link (x, y);} void UFS :: link (int x, int y) {P [x] = y; depth [x] = 1; rank [y] + = rank [X];} void UFS :: graft (int r, int v) {int x = find_set (r); int y = find_set (V); If (x <Y) Union (x, y ); elseunion (Y, x );}