Disjoint sets
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 1
Disjoint sets March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey - - PowerPoint PPT Presentation
Disjoint sets March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 1 A data structure for disjoint sets Maintains a collection = 0 , 1 , , of disjoint sets Each set has a representative member Required
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 1
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 2
index representative 1 2 3 4 5 6 7 2 3 3 3 2 Cost of Find()? Cost of Union()?
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 3
β1 β1 β1 β1 index parent 1 2 3 1 2 3 1 β1 β1 2 index parent 1 2 3 1 2 3 1 β1 1 2 index parent 1 2 3 1 2 3
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 4
int DisjointSets::Find(int x) { if (parent[x] < 0) return x; else return Find(parent[x]); } Running time?
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 5
1 2 3 Union(0, 1); Union(1, 2); Union(0, 3); 1 2 3 Can still end up with bad trees!
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 6
7 6 9 2 8 3 4 1 11 5 10 6 6 6 8 10 7 index parent 1 2 3 4 5 6 7 7 7 4 5 8 9 10 11 6 6 6 8 10 7 index parent 1 2 3 4 5 6 7 7 7 4 5 8 9 10 11 Union by height Keeps overall tree height as small as possible Union by size Increases distance from root for as few nodes as possible 4 7
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 7
4 11 5 10 7 Find(5); 4 11 5 10 7 Find(10);
March 20, 2020 Cinda Heeren / Andy Roth / Geoffrey Tien 8