Two optimizations for query set: merge by rank and compression by path to optimize merge path compression
The query set has two optimizations.
I. merge by rank
Description: it is connected to two different subsets according to rank, that is, the low rank is connected to the high rank. Rank is a Father's Day.
This is similar to maintaining a tree where the tree is on top of the rank.
// Initialize n elements void init (int n) {for (int I = 0; I <n; I ++) {parent [I] = I; rank [I] = 0; // The height of the initial tree is 0} // combines the void unite (int x, int y) of the Set to which x and y belong) {x = find (x); y = find (y); if (x = y) return; if (rank [x] <rank [y]) parent [x] = y; // the merge is from a small rank to a large rank edge else {parent [y] = x; if (rank [x] = rank [y]) rank [x] ++ ;}}
Ii. path compression
Description: If the fa array has nested N layers, the traditional method is to find the ancestor for N times. When N is large, this method is inefficient.
This isSimple searchCode,Suitable for scenarios with a small amount of data:
int findx(int x){ int r=x; while(parent[r] !=r) r=parent[r]; return r;}
Below isRecursive path compressionBut,Recursive compression path may cause Stack Overflow,RE occurs..
Int find (int x) // finds the set of x elements, and compresses the path {if (x! = Parent [x]) {parent [x] = find (parent [x]); // The compression path during backtracing} // search from the x node and find that all the nodes that have passed through the ancestor node point to the ancestor node return parent [x];}
Let's talk aboutNon-recursive path compression:
Int find (int x) {int k, j, r; r = x; while (r! = Parent [r]) // find the following node r = parent [r]; // locate the following node and use r to record k = x; while (k! = R) // non-recursive path compression operation {j = parent [k]; // use j to store parent [k] parent node parent [k] = r; // parent [x] points to the following node k = j; // k moves to the parent node} return r; // returns the value of the root node}