并查集、等价类、不相交集合
本文为本人学习过程中整理的学习笔记,想顺带学英语所以用英文呈现。发现错误还烦请指正。欢迎交流。
未经同意,请勿转载
Disjoint Set
Equivalence Relations
Dynamic Equivalence Problem
Disjoint Set
Pick a element to be the symbol of the disjoint set.
Find
Return the root of the disjoint set structure.
-
Simple Find
DisjSetType find(DisjSetType x, DisjSets s){ while(s[x] > 0) x = s[x]; return x; }
-
Path Compression
Visiting RED node with pointing all the upstream nodes to the root, which is slower for a single finding, but faster for a sequence of finding operations.
Not compatible with union-by-height since it changes the heights. Just take “height” as an estimated rank.
-
Recursive Version
DisjSetType Find(DisjSetType x, DisjSets s){ if(s[x] <= 0) return x; else return s[x] = find(s[x], s); }
-
Iterative Version
DisjSetType Find (DisjSetType x, DisjSets s){ DisjSetType root, trail, lead; for(root = x; s[root] > 0; root = s[root]) ; for(trail = x; trail != root; trail = lead){ lead = s[trail]; s[trail] = root; } root; }
-
Union
-
Simple Union
void union(DisjSetType s1, DisjSetType s2, DisjSets s){ s[find(s2)] = s[s1]; }
-
Smart Union
Store the size or height information as negative number (invalid index) in root.
-
Union by Size: Always change the smaller tree
S[root] = -size_of_tree
-
Union by Height: Always change the shallow tree
S[root] = -height_of_tree
-