Algorithms - Priceton - 01 - Dynamic Connectivity & Union Find
Connected components : Maximal set of objects that are mutually connected.
Find query : Check if two objects are in the same component.
Union command : Replace components containing two objects with their union.
----------------------------------------------------------------------------------------------------------
Quick-find [eager approach]
Data structure :
- Integer array id[] of size N.
- Interpretation: p and q are connected if and only if they have the same id.
Find : Check if p and q have the same id. O(1)
Union : To merge components containing p and q, change all entries whose id equals id[p] to id[q]. O(N)
----------------------------------------------------------------------------------------------------------
Quick-union [lazy approach]
Data structure :
- Integer array id[] of size N.
- Interpretation : id[i] is parent of i.
- Root of i is id[id[id[...id[i]...]]].
Find : Check if p and q have the same root. O(height)
Union : To merge components containing p and q, set the id of p's root to the id of q's root. O(height)
----------------------------------------------------------------------------------------------------------
Improvement 1 to quick-union : weighting
Weighted quick-union :
- Modify quick-union to avoid tall trees.
- Keep track of size of each tree(number of objects).
- Balance by linking root of smaller tree to root of larger tree.
Data structure :
Same as quick-union, but maintain extra array sz[i] to count number of objects in the tree rooted at i.
Find : Identical to quick-union. O(lgN)
Union : Modify quick-union to O(lgN)
- Link root of smaller tree to root of large tree.
- Update the sz[] array.
----------------------------------------------------------------------------------------------------------
Improvement 2 : path compression
Quick-union with path compression : Just after computing the root of p,
set the id of each examined node to point to that root. much closer to linear
posted on 2013-10-06 15:48 haoyancoder 阅读(192) 评论(0) 收藏 举报
浙公网安备 33010602011771号