This section is about the second method of implementing and checking the set. The cost of merging operations for such a method is very small, but the cost of finding operations is very high.
Data
The data structure of such an algorithm is the same as that of a high-speed lookup method, and is an array of n integers.
Each element in the array id[i] means that the ancestor of I is id[i].
Root node
The root node of a node is id[id[id[...id[i]]], which loops until the value no longer changes. Because of the characteristics of the algorithm, such loops never cause a dead loop.
Find operations
The lookup operation is to infer whether the root node of the two nodes is the same.
Merge operations
Merging node p and node q is the parent node of the root node of the P node set to the root node of the Q node. This only needs to change a value, so the overhead is much less.
Complexity of
This approach, although a lot of performance improvements, is still not enough, due to the worst case, the complexity of the lookup operation will reach N.
Control
The cost of merging in a high-speed lookup method is too large, but the established tree structure is flat, so the cost of finding operations is minimal, but it is expensive to build a flat tree in a merge operation.
The tree structure in a high-speed merge method can be very high. In this case, the lookup operation is expensive and the complexity can reach N.
Princeton Open Class algorithm 1-9: And check set-high-speed merger