Query set path compression and heuristic merge

Source: Internet
Author: User

 

 

 

Program list 〗

 

 

 

Initialization:

 

For I: = 1 to n do father [I]: = I;

 

Because each element belongs to a separate set, each element uses itself as the root node.

 

Search for the root node number and compress the path:

 

Function getfather (V: integer): integer;

 

Begin

 

If father [v] = V then exit (v );

 

Father [v]: = getfather (father [v]);

 

Getfather: = Father [v];

 

End;

 

Merge two sets:

 

Proceudh Merge (X, Y: integer );

 

Begin

 

X: = getfather (X );

 

Y: = getfather (y );

 

Father [x]: = y;

 

End;

 

Determine whether an element belongs to the same set:

 

Function judge (X, Y: integer): Boolean;

 

Begin

 

X: = getfaher (X );

 

Y: = gefather (y );

 

If X = y then exit (true)

 

Else exit (false );

 

End;

 

Here is an optimization: Let the tree with a smaller depth become the child tree of a larger depth, so that the number of queries will be less. This optimization is called heuristic merge. It can be proved that the depth of the tree is O (logn) after this is done ). That is, in a set with n elements, we can find the target without moving more than N logstores.

 

Function judge (X, Y: integer): Boolean;

VaR FX, FY: integer;

Begin

FX: = getfaher (X );

FY: = gefather (y );

If FX = FY then

Exit (true) else

JUDGE: = false;

If rank [FX]> rank [FY] Then

Father [FY]: = FX else begin

Father [FX]: = FY;

If rank [FX] = rank [FY] Then

INC (rank [FY]);

End;

End;

Initialization:

Fillchar (rank, sizeof (rank), 0 );

 

 

And query the time complexity of the Set

 

The time complexity of querying the set for N queries is O (n)

 

 

It is an inverse function of Ackermann Function.

It can be considered as less than 5. Therefore, we can think that the time complexity of the query set is almost linear.

 

 

 

 

 

Query set path compression and heuristic merge

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.