问题
Here's a breakdown on the union/find algorithm for disjoint set forests on wikipedia:
- Barebone disjoint-set forests... (
O(n)
)- ... with union by rank ... (now improved to
O(log(n)
)- ... with path compression (now improved to
O(a(n))
, effectivelyO(1)
)
- ... with path compression (now improved to
- ... with union by rank ... (now improved to
Implementing union by rank necessitates that each node keeps a rank
field for comparison purposes. My question is, is union by rank worth this additional space? What happens if I skip union by rank and just do path compression instead? Is it good enough? What is the amortized complexity now?
A comment is made that implies that union by rank without path compression (amortized O(log(n)
complexity) is sufficient for most practical application. This is correct. What I'm asking is the other way around: what if you skip union by rank and ONLY do path compression instead?
In a sense, path compression is an extra step to improve union by rank, and that's why that extra step can be omitted without disastrous consequence. But is union by rank a necessary intermediate step to path compression? Can I skip it and go straight to path compression, or will that be catastrophic?
It was also pointed out that without union by rank, repeated unions could create a linked-list like structure. This means that a single path compression operation could take O(n)
in the worst case. This would of course affect future operations, so how this plays out when amortized over many operations is what I'm more interested in.
回答1:
I googled for "without union by rank" and the second link that came up was this one:
...We close this section with an analysis of union–find with path compression but without union by rank...
The union-find datastructure with path compression but without union by rank processes m find and n-1 link operations in time O((m+n) log n)
回答2:
Path compression flattens the tree structure. Union by rank helps to merge. Assume that you skip the latter. So now, you have a forest with no rank information to choose how to merge. Potentially, you now run the risk of merging a tree with a larger depth to one with a smaller depth -- leading to an unbalanced tree structure. In the worst case, you may end up with a linked list. Your Union's amortized time complexity increases even if that for Find remains the same.
IMO, It'd be better to skip path compression but not rank.
来源:https://stackoverflow.com/questions/2323351/union-find-algorithm-without-union-by-rank-for-disjoint-set-forests-data-structu