and check set path compression

Source: Internet
Author: User

This is the code of the simple lookup, suitable for the case of small amount of data:

int findx (int x)
{
int r=x;
while (Parent[r]!=r)
R=PARENT[R];
return R;
}

Here's how to find the element using path compression:

int find (int x)       //Find the collection where the X element resides, and compress the path when backtracking
{
if (x! = Parent[x])
{
PARENT[X] = find (parent[x]); The compression path when backtracking
} //The nodes that pass from the X-node search to the ancestor node point to the Ancestor node.
return parent[x];
}

The above is a recursive way to compress the path, but the recursive compression path may cause overflow stack, I used to because of this re n times, below we say a non-recursive way to do the path compression:

int find (int x)
{
int K, j, R;
R = x;
while (r! = Parent[r]) //Lookup and Node
r = parent[r]; Find the node and use R to record
k = x;
while (k! = r) //non-recursive path compression operation
{
j = Parent[k]; The parent node of the J staging Parent[k]
Parent[k] = r; PARENT[X] Point and Node
K = J; K Move to parent node
}
return R; Returns the value of the root node
}

(turn) and set path compression

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.