Upload
josiah-clack
View
220
Download
1
Embed Size (px)
Citation preview
2
Union-find
• Maintain a collection of disjoint sets under the following two operations
• S3 = Union(S1,S2)
• Find(x) : returns the set containing x
3
Union-find
• We assume there are n fixed elements
• We start with n sets each containing a single element
• Each element has a pointer to its representation in the set containing it
4
S1 = {e1} S2 = {e2} S3={e3} S4={e4} ……
S1 = {e1} A= {e2,e3} S4={e4} ……
A = Union(S3,S4)
Find(e2) A
B = Union(A,S7)
S1 = {e1} B= {e2,e3,e7} S4={e4} ……
9
Can solve this with union-find
• Each equivalence class is a set
• y ≡ s union(find(y),find(s))
• Equivalent?(y,a) return yes if find(y) = find(a)
10
e2
Representation
• Represent each set by a tree, each node represents an item, the root also represents the set
e3e7
B
21
D=Union(B,C)
Be2
e3e7
C e6
e9e11
e8e10
5
3
If (C.size > B.size) then B.Parent ← C; C.size = C.size + B.size return (C)Else C.parent ← B; B.size = B.size + C.size return (B)
22
D=Union(B,C)
Be2
e3e7
C e6
e9e11
e8e10
8
3
If (C.size > B.size) then B.Parent ← C; C.size = C.size + B.size return (C)Else C.parent ← B; B.size = B.size + C.size return (B)
D