Documente Academic
Documente Profesional
Documente Cultură
Disjoint Sets
• Some applications require maintaining a collection
of disjoint sets.
• Union(x,y) – Replaces S x , S y by S x S y
one of the elements of S x S y becomes the
representative of the new set. O(log n) time.
e f h j
g i
a b
c d
(b,d)
e f h j
g i
a b
c d
(e,g)
e f h j
g i
a b
c d
(a,c)
e f h j
g i
a b
c d
(h,i)
e f h j
g i
a b
c d
(a,b)
e f h j
g i
a b
c d
(e,f)
e f h j
g i
a b
c d
(b,c)
e f h j
g i
a b
c d
Result
e f h j
g i
a b
c d
Connected Components
a b c d
Union with linked lists
a b c d
+
e f g
e f g a b c d
5
Analysis
• Using linked list, MAKE_SET and
FIND_SET are constant operations,
however UNION requires to update the
representative for at least all the elements of
one set, and therefore is linear in worst case
time
d
Make Set
• MAKE_SET(x)
p(x)=x
rank(x)=0
x
Find Set
• FIND_SET(d)
if d != p[d]
p[d]= FIND_SET(p[d])
return p[d]
a b f
d
Union
w
c
• UNION(x,y) x
link(findSet(x), a b f
findSet(y)) y
• link(x,y) d z
if rank(x)>rank(y)
then p(y)=x
else c w
p(x)=y
if rank(x)=rank(y) a b f x
then rank(y)++
y
d
z
Analysis
• In Union we attach a smaller tree to the larger tree,
results in logarithmic depth.
7
1 2 3 4 5 6 .. N
Parent 4 7 4 4 7 6 2 5
min 1 6
Example
• Executing union(4,6)
4 6
3 1
7
1 2 3 4 5 6 .. N
Parent 4 7 4 4 7 4 2 5
min 1 1
Exercise
• Describe a data structure that supports the
following operations:
– Union (8,4) 1 2 3 4 5 6 7 8 9 10
– Find(2) parent 4 7 7 4 8 1 5 8 1 4
– Find(6)
– DeUnion()