Two optimizations (rank optimization + path compression) for a set

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.