Union-find Sets)

Source: Internet
Author: User

Union-find Sets)

Union-find sets are a simple and widely used set. the query set is a set of several non-intersecting sets, which can be used to quickly merge and determine the set where elements are located. Generally, a tree structure is used to store and query sets, and a rank array is used to store the depth lower bound of the set. path compression is performed during search operations to accelerate subsequent search operations. In this way, we can optimize and query the set. The space complexity is O (n), and the time complexity of building a set is O (1 ), the time complexity of N merge M searches is O (M alpha (N). Here Alpha is an inverse function of the Ackerman function, within a very large range (the universe we have observed is estimated to have 10 to 80 atoms, which is smaller than the previously mentioned range) the value of this function can be regarded as not greater than 4, so the query set operation can be regarded as linear. It supports the following three operations:

-Union (root1, root2) // merge the sub-set root2 into the set root1. Requirement: root1 and root2 are mutually exclusive; otherwise, no operation is performed.

-Find (x) // search operation. Search for the set where single element x is located and return the name of the set.

-Ufsets (s) // constructor. Initialize s elements in the query set to s child sets with only one single element.

-For the Union query, each set is represented by a tree.

-The element names of each element in the set are respectively stored in the node of the tree. In addition, each node of the tree has a pointer to its parent node.

-Set S1 = {0, 6, 7, 8}, S2 = {1, 4, 9}, S3 = {2, 3, 5}



-To simplify the discussion, ignore the actual Set Name and only use the root of the tree that represents the set to identify the set.

-For this reason, the tree parent representation is used as the set storage representation. The number of the Set element ranges from 0 to n-1. N indicates the maximum number of elements. In the parent representation, the I-th array element represents the tree node that contains the set element I. The parent node of the root node is-1, indicating the number of elements in the set. To distinguish the parent pointer information (≥0), the number of elements in the set is expressed as a negative number.


Subscript

Parent

The dual-parent representation of S1, S2, and S3:

Possible representation of S1 ipvs2

Const int defaultsize = 10;
Class ufsets {// check the class definition of the Set
PRIVATE:
Int * parent;
Int size;
Public:
Ufsets (int s = defaultsize );
~ Ufsets () {Delete [] parent ;}
Ufsets & operator = (ufsets const & value); // set value assignment
Void Union (INT root1, int root2 );
Int find (int x );
Void unionbyheight (INT root1, int root2 );};
Ufsets: ufsets (INT s) {// Constructor
Size = s;
Parent = new int [size + 1];
For (INT I = 0; I <= size; I ++) parent [I] =-1;
}
Unsigned int ufsets: Find (int x) {// search operation
If (parent [x] <= 0) return X;
Else return find (parent [x]);
}
Void ufsets: Union (INT root1, int root2) {// and
Parent [root2] = root1; // root2 points to root1
}



Find and Union operations have poor performance. Assume that n elements constitute a forest composed of N trees. Parent [I] =-1. Processing Union (0, 1), Union (1, 2 ),..., After Union (n-2, n-1), a degraded tree will be generated.



The time required for executing a union operation is O (1), and the time required for n-1 Union operations is O (n ). If you execute find (0), find (1 ),..., Find (n-1), if

The search element is I, and the time required to complete the find (I) operation is O (I). The total time required to complete n searches will reach



Weighted rules for Union operations

To avoid tree degradation, the improvement method is to first determine the number of elements in the two sets. If the number of nodes in the tree with "I" as the root is less than the number of nodes in the tree with "J" as the root, that is, parent [I]> parent [J] (parent [] <0) makes J the parent of I. Otherwise, let I become the parent of J. This is the weighted rule of union.

Parent [0] (=-4) <parent [4] (=-3)

Void ufsets: weightedunion (INT root1, int root2 ){
// Algorithm improved based on the weighted union rules
Int temp = parent [root1] + parent [root2];
If (parent [root2] <parent [root1]) {
Parent [root1] = root2; // multiple knots in root2
Parent [root2] = temp; // root1 points to root2
}
Else {
Parent [root2] = root1; // multiple knots in root1
Parent [root1] = temp; // root2 points to root1
}
}



Tree obtained using weighted rules


Below are some problems that can be easily solved by using and querying the set:


Question: Relations)

Maybe you don't know. One of your friends is your relative. He may be the grandson of your great-grandfather's son-in-law's nephew. If a complete family tree can be obtained, it is feasible to determine whether two people are relatives or not. However, if the recent common ancestor of two people is several generations separated from them, the family tree is very huge, then we can test the relationship between relatives. in this case, the best helper is the computer.

To simplify the problem, you will get information about the kinship, such as marry and Tom, and Tom and B en. From this information, you can introduce that marry and Ben are relatives. Please write a program to give answers to questions about our relatives as quickly as possible.

The input in reference input/output format is composed of two parts.

The first part starts with N, M. N is the number of persons involved in the problem (1 ≤ n ≤ 20000 ). The numbers of these persons are 1, 2, 3 ,..., N. Below are m rows (1 ≤ m ≤ 1000000), each row has two numbers of AI, Bi, indicating that known AI and Bi are relatives.

The second part starts with Q. The following Q rows contain Q queries (1 ≤ q ≤ 1 000 000). Each behavior CI, Di, indicates asking whether Ci and Di are relatives.

For each query CI, Di, If Ci and Di are relatives, yes is output; otherwise, no is output.

Sample Input and Output

Enter relation. In

10 7

2 4

5 7

1 3

8 9

1 2

5 6

2 3

3

3 4

7 10

8 9

Output relation. Out

Yes

No

Yes

If this question does not need to check the set, but only uses a linked list or array to store the set, the efficiency is very low and it will definitely time out.

Routine:

# Include <iostream>
Using namespace STD;
Int n, m, Q;
Int pre [20000], rank [20000];
Void makeset (int x)
{
Pre [x] =-1; // start with the root node
Rank [x] = 0; // The depth is 0.
}
Int find (int x)
{
Int r = X;
While (pre [R]! =-1) r = pre [R]; // accelerated search similar to recursion
While (X! = R) // set the root node to R (unified set name)
{
Int q = pre [x];
Pre [x] = R;
X = Q;
}
Return R;
}
Void unionone (int A, int B)
{
Int T1 = find ();
Int t2 = find (B );
If (rank [T1]> rank [T2]) //?
Pre [T2] = T1;
Else
Pre [T1] = t2;
If (rank [T1] = rank [T2])
Rank [T2] ++;
}
Int main ()

{
Int I, a, B, c, d;
While (CIN> N> m)
{
For (I = 1; I <= N; I ++)
Makeset (I );
For (I = 1; I <= m; I ++)
{
Cin> A> B;
If (find ()! = Find (B ))
Unionone (A, B );
}
Cin> q;
For (I = 1; I <= Q; I ++)
{
Cin> C> D;
If (find (c) = find (d ))
Cout <"yes" <Endl;
Else
Cout <"no" <Endl;
}
}
Return 0;
}

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.