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