I haven't quite understood and checked the path compression, and I always use one way of writing.
A general loop lookup is followed by:
int find (int x){ while (x != father[x]){ x = father[x]; } return x; }
Find recursively:
int find (int x){ if(x == father[x]){ return x; } else{ return find( father[x]); } }
Recursion of path compression:
int find(int x) { //Find the set where the x element is located, and compress the path when backtracking if (x != father[x]){ father[x] = find(father[x]); //compression path when backtracking } //The nodes passed from the x node search to the ancestor node all point to the ancestor node return father[x]; }
Path compression non-recursive:
int find(int x){ int k, j, r; r = x; while(r != father[r]) { //Find the follower node r = father[r]; //Find the follower node and record it with r } k = x; while(k != r){ //Non-recursive path compression operation j = father[k]; //Use j to temporarily store the parent node of parent[k] father[k] = r; //parent[x] points to the follower node k = j; //k moves to the parent node } return r; //return the value of the root node }