Professional Documents
Culture Documents
DAA U-2(part1)
DAA U-2(part1)
Dr.B.Srinu
Disjoint Sets 2
Disjoint Set
Sets and Disjoint Set :
Disjoint Set Union:
Considering a set S={1,2,3…10} (when n=10),
then elements can be partitioned into three disjoint
sets
s1={1,7,8,9}, s2={2,5,10} and s3={3,4,6}.
Disjoint Sets 3
Disjoint Set Union/Find
Disjoint Sets 4
Disjoint Set Union/Find ADT
Union/Find ADT operations
union find(4)
find {1,4,8} {6}
create
destroy 8 {7} {2,3,6}
{5,9,10}
{2,3}
union(2,6)
Disjoint set equivalence property: every element of a DS U/F
structure belongs to exactly one set
Dynamic equivalence property: the set of an element can
change after execution of a union
2 1 6
find(b) b
find(e) e
d 4 e 7 f
find(b) find(e) so:
add 1 to E 11 9 8
union(b, e)
g 12 h 5 i
{a}{b,e}{c}{d}{f}{g}{h}{i}
Order of edges in blue
d e 7 f
d b f i 11 9 8
g 12 h i
e
a b 10 c
a c g h
d e f
d b f i 11 9 8
g 12 h i
e
Example (1/11)
2 1 6
d 4 e 7 f
11 9 8
union(b,e) g 12 h 5 i
a b c d e f g h i
a b c d f g h i
e
a 3 b 10 c
Example (2/11)
2 6
d 4 e 7 f
11 9 8
union(a,d) g 12 h 5 i
a b c d f g h i
e
a b c f g h i
d e
a 3 b 10 c
Example (3/11)
6
d 4 e 7 f
11 9 8
union(a,b) g 12 h 5 i
a b c f g h i
d e
a c f g h i
b d
e
a b 10 c
Example (4/11)
6
d 4 e 7 f
11 9 8
find(d) = find(e) g 12 h 5 i
No union!
a c f g h i
b d
e
Example (5/11)
6
d e 7 f
11 9 8
union(h,i) g 12 h 5 i
a c f g h i a c f g h
b d b d i
e e
a b 10 c
Example (6/11)
6
d e 7 f
11 9 8
union(c,f) g 12 h i
a c f g h a c g h
b d i b d f i
e e
a b 10 c
Example (7/11) d e 7 f
find(e)
find(f) 11 9 8
union(a,c) g 12 h i
a c g h c g h
b d f i a f i
e b d
Could we do a
better job on this union? e
a b 10 c
Example (8/11) d e f
find(f)
find(i) 11 9 8
union(c,h) g 12 h i
c g h c g
a f i a f h
b d b d i
e e
a b 10 c
Example (9/11) d e f
find(e) = find(h) and find(b) = find(c) 11 9
So, no unions for either of these. g 12 h i
c g
a f h
b d i
e
a b c
Example (10/11) d e f
find(d)
find(g) 11
union(c, g) g 12 h i
c g g
c
a f h
a f h
b d i
b d i
e e
a b c
Example (11/11) d e f
find(g) = find(h)
So, no union.
And, we’re done! g 12 h i
g a b c
c d e f
a f h
g h i
b d i
Ooh… scary!
e Such a hard maze!
Disjoint set data structure
A forest of up-trees
can easily be stored a c g h
in an array.
Also, if the node b d f i
names are integers or
characters, we can
use a very simple, e
perfect hash.
Nifty storage trick!
0 (a) 1 (b) 2 (c) 3 (d) 4 (e) 5 (f) 6 (g) 7 (h) 8 (i)
up-index: -1 0 -1 0 1 2 -1 -1 7
a c g h c g h a g h
b d f i a f i b d c i
e b d e f
Could we do a e
better job on this union?
Weighted union!
a c f g h i a c f g h i
b d b d
e e
While we’re finding e,
could we do anything else?
Path compression!
c g c g
a f h a f h
b e
b d
d
i
i e