Path compression
recursion is used when searching for ancestors, but once the elements are more or degenerate into a chain, each getfather will use O (n) complexity, which is obviously not what we want. In this case, we have to do path compression, that is, when we find the oldest ancestor, "by the way," it connects its descendants directly to it. This is the path compression. The code for using path compression is as follows, the time complexity base
Could have been considered a constant.
path compression can be implemented iteratively and recursively recursively, but some topics explode.
Recursive form of path compression int getf (int v) { if (V==f[v]) return v; Return F[V]=GETF (F[v]);}
Iterative form of path compression int getf (int v) { int p = V, t; while (f[p]! = p) p = f[p];//found ancestor p while (v! = p) {t = f[x]; f[x] = p; x = t;}//path compression return v;}
Merge by RankIt is also possible to apply a simple heuristic strategy-merging by rank. The method uses rank to represent the upper bound of the height of the tree, and at merge time, the root with the smaller rank is always pointed to the root with a larger rank. Simply put, the dwarf tree is always added to the higher tree as a subtree. In order to save the rank, an additional array of the same length as uset is required, and all elements are initialized to 0. This way the ancestors will reduce the number of recursive iterations, the worst is only logn times.
void Merge (int x,int y) { int t1=getf (x), t2=getf (y); if (T1==T2) return,//has been merged to return if (rnk[t1]>rnk[t2]) f[t2]=t1; The ancestors of y were T2 and T1 to the ancestors of X. Because the tree with the root of T1 is higher else { f[t1]=t2; if (Rnk[t1]==rnk[t2]) rnk[t2]++; If the two trees are the same height, then the combination of the Heights plus one. }}
Two optimizations (rank optimization + path compression) for a set