11.DisjointSets
11.DisjointSets
CONNECTED-COMPONENTS(G) SAME-COMPONENT(u,v)
1. for each vertex v V[G] 1. if FIND-SET(u)=FIND-SET(v)
2. do MAKE-SET(v) 2. then return TRUE
3. for each edge (u,v) E[G] 3. else return FALSE
4. do if FIND-SET(u) FIND-SET(v)
5. then UNION(u,v)
Linked-List Implementation
• Each set as a linked-list, with head and tail, and
each node contains value, next node pointer and
back-to-representative pointer.
• Example:
• MAKE-SET costs O(1): just create a single
element list.
• FIND-SET costs O(1): just return back-to-
representative pointer.
Linked-lists for two sets
Set {c,h,e}
head c h e
tail
c cf cf
h e d c d
c
Algorithm for Disjoint-Set Forest
UNION(x,y)
MAKE-SET(x) 1. LINK(FIND-SET(x),FIND-SET(y))
1. p[x]x FIND-SET(x)
2. rank[x]0 LINK(x,y) 1. if x p[x]
1. if rank[x]>rank[y]
2. then p[y] x 2. then p[x] FIND-SET(p[x])
3. else p[x] y 3. return p[x]
4. if rank[x]=rank[y]
5. then rank[y]++
Worst case running time for m MAKE-SET, UNION, FIND-SET operations is:
O(m(n)) where (n)4. So nearly linear in m.