Operations that do not intersect a collection
Some applications involve dividing n different elements into a set of disjoint sets, often doing two things: looking for a unique collection that contains the elements to be made, and merging two collections. The actions are set out below:
Make-set (x) creates a new set that contains only the X
Union (x, y) merges two sets containing x and y into a new collection, deleting the original collection
Find-set (x) returns a pointer to a collection that contains a unique X
The connected component of undirected graphs is an example.
For the 4 connected components, a separate set is established for each individual point, then the corresponding set is merged according to each edge in turn, and 4 disjoint sets are formed at the end.
1 connected-components (e,v) {// Span style= "COLOR: #008000" > E[n] vertices v[m] Sidebar 2 for (I=0 ; I<n;i++ 3 make-set (V[i]); 4 for (I=0 ; I<m;i++ 5 if (find-set (v[i].u! = Find-set (V[I].V)) 6 UNION (V[I].U,V[I].V); 7 } 8 }
A linked list representation of disjoint collections
(a) The structure shown is formed by the disjoint set to form a linked list, the index head contains the list of the head and tail, the list of nodes each node contains a pointer to the index head and the next node two pointers. For this structure, Make-set (x) and Find-set (x) can be completed at O (1) time.
(b) The operation of union (x, y) is shown, the other linked list needs to be connected to the end of a linked list, then the tail of the index node is modified, and the index header pointed to by each node of the merged list is modified so that the operation takes at least O (Y) time
To reduce the time to merge, you can store the size of each linked list in the head, so that you can merge small collections into large collections.
Disjoint collection Forest
Use a root tree to represent the collection, each node in the book contains a member, a tree represents a collection, each member points to his parent node, and the parent node of the root node points to itself.
(b) It is a merger, and the father of C is changed to F. The structure of this disjoint aggregate forest is make-set and union efficient, but the find-set receives a tree height effect and is less efficient. Therefore, there are two kinds of improved heuristic algorithms.
The first is to merge by rank, and for each node to record his height, change the father of the smaller node to the larger one. If both sides are equal, select one as the father, and the rank of the root node plus one.
The second is path compression, and each time the find-set is called, the father of the node found on the path is changed directly to the root node.
1make-SET (x) {2X.P =x;3X.rank =0;4 }5 6 UNION (x, y) {7 if(X.rank >Y.rank)8Y.P =x;9 Else{TenX.P =y; One if(X.rank = =Y.rank) Ay.rank++; - } - } the -find-SET (x) { - if(X! =x.p) -X.P = find-SET (x,p); + returnX.P; -}
An introduction to algorithms--data structures for disjoint collections