Algorithm traces---and check set

Source: Internet
Author: User

Template

1. Initialization

2. Find the root node

3. Merging

int per[1100];void init () {for (int  i =1; I <= N; ++i) Per[i] = i;//initialization  At first each node is independent of the parent node is itself}int find (int x) {if (x = = Per[x])//recursive return X;return per[x] = find (Per[x]);} can be shortened into//return x==per[x]?

X:per[x]=find (Per[x]); void join (int x, int y) {//merge two nodes int fx = find (x); int fy = find (y); if (FX! = FY)//Assume X. The root node of y is different per[fx] = fy;//Connect two root nodes}//as to which node to connect to, look at depth, can open the number of groups. It is an optimal way to connect a small depth to a large depth. When the data is big, it can be enough


The Find function looks for the root node and there are two ways to implement it:

int find (int x) {int r = x;while (r! = Per[r]) R = per[r];//update node until R=per[r]  (parent node of root node is itself) int I, j;i = X;while (i! = r) {// Path compression j = per[i];//Save the next node, that is, the parent node of the current node per[i] = r;//assigns the parent node of the current node to the root node i = j;//update node}return r;//returns the root node}  //or int find (in T x) {int r = x;while (r! = Per[r]) R = per[r];p er[x] = r;//make R the parent of x one step}  


The following are recursive optimized path merges:

void join (int x, int y) {    int fx = find (x);    int fy = find (y);    if (FX = = FY)        return;    if (Ran[fx] < Ran[fy])//The depth of the small tree to the depth of the number if the depth of the two trees is h1,h2         per[fx] = fy;//The combined number of the height H:max (h1,h2), if H1<>H2     else{            //h1+h2,if h1=h2             per[fy] = FX;        if (ran[fx] = = Ran[fy]) ran[fx]++;    }}


Algorithm traces---and check set

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.