定义
等价关系
- 【Definition】A relationR is defined on a set S if for every pair of elements (a, b), a, b ∈S, a R b is either true or false. If a R b is true, then we say that a is related to b.
- 【Definition】A relation,
~
, over a set, S, is said to be an equivalence relation over S iff it is symmetric, reflexive, and transitive over S. - 【Definition】Two members x and y of a set S are said to be in the same equivalence class iff x ~ y.
不相交集
Example: _S_1 = { 6, 7, 8, 10 }, _S_2 = { 1, 4, 9 }, _S_3 = { 2, 3, 5 }
指针由children到parents。
操作
Union(i, j)
Si∪Sj
Implementation1
Implementation2
假设数字是1到n,这样数字可以用作数组下标。
S [ element ] = the element’s parent
PS:这种Union不是最好的,有可能会增加树的高度。
Find(i)
找到含元素i的集合Sk
Smarter Ways to Do Union
按大小求并 | Union-by-Size
Lemma:若Union均按大小进行,则任何节点的深度均不会超过。
具体操作方法是每个根的数组元素包含它的树的大小的负值,每执行一次Union时,要更新树的大小,新的大小为老的大小之和。通过这种方式,N次Union和M次Find的时间复杂度为。
按高度(秩)求并 | Union-by-Height
这种方式求并同样可以保证所有的树深度最多是。他可以使较浅的树成为较深的树的子树,并且只有在两棵树高度相等合并时树的高度才增加1。
具体操作方法是每个根的数组元素包含它的树的高度的负值,每执行一次Union时,要更新树的大小,新的大小为老的大小之和。
Smarter Way to Do Find
路径压缩 | Path Compression
从X到根的路径上的每一个节点,都使其父节点变成根。
SetType Find ( ElementType X, DisjSet S )
{ ElementType root, trail, lead;
for ( root = X; S[ root ] > 0; root = S[ root ] )
; /* find the root */
for ( trail = X; trail != root; trail = lead ) {
lead = S[ trail ] ;
S[ trail ] = root ;
} /* collapsing */
return root ;
}
SetType Find ( ElementType X, DisjSet S ){
if ( S[ X ] <= 0 ) return X;
else return S[ X ] = Find( S[ X ], S );
}
重要
路径压缩与按大小求并兼容,可以同时实现,而与按高度求并不兼容,因为压缩的过程改变了树的高度。