动态连接 并查集
Union command 连接两个物体
网络,社交网络,
实现查找和合并
1 | public class UF{ |
快速查找 quick-find
p和q连通,则id[p]=id[q]
1 | public class QuickFindUF{ |
Quick-union[lazy approach]
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
Union : To merge compoents p and q,set the id of p’s root to the id of q’s root
1 | public class QuickUnionUF{ |
Quick-Union improvements
Weigthed quick-union
- modify quick-union to avoid tall tree.
- keep track of size of each tree(number of objects).
- balance by linking root of smaller tree to root of larger tree.
数据结构:和quick-union一样,但是维护一个额外数组sz[i]来计算以i为根的树包含的对象个数。
Find : Identical to quick-union
Union : 主要有两处改变
- Link root of smaller tree to root of larger tree.
- Update the sz[] array.
1 | public class WeightedQuickUnionUF{ |
带路径压缩的quick-union、
Quick union with path compression
- just after computing the root of p,set the id of examined node to point to that root.
Two-pass implementation
- add second loop to root() to set the id[] of each examined node to the root.
Simpler one-pass variant
- Make every other node in path point to its grandparent(thereby halving path length)
1 | private int root(int i){ |