|
| 1 | +""" |
| 2 | +Implements a disjoint set using Lists and some added heuristics for efficiency |
| 3 | +Union by Rank Heuristic and Path Compression |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +class DisjointSet: |
| 8 | + def __init__(self, set_counts: list) -> None: |
| 9 | + """ |
| 10 | + Initialize with a list of the number of items in each set |
| 11 | + and with rank = 1 for each set |
| 12 | + """ |
| 13 | + self.set_counts = set_counts |
| 14 | + self.max_set = max(set_counts) |
| 15 | + num_sets = len(set_counts) |
| 16 | + self.ranks = [1] * num_sets |
| 17 | + self.parents = list(range(num_sets)) |
| 18 | + |
| 19 | + def merge(self, src: int, dst: int) -> bool: |
| 20 | + """ |
| 21 | + Merge two sets together using Union by rank heuristic |
| 22 | + Return True if successful |
| 23 | + Merge two disjoint sets |
| 24 | + >>> A = DisjointSet([1, 1, 1]) |
| 25 | + >>> A.merge(1, 2) |
| 26 | + True |
| 27 | + >>> A.merge(0, 2) |
| 28 | + True |
| 29 | + >>> A.merge(0, 1) |
| 30 | + False |
| 31 | + """ |
| 32 | + src_parent = self.get_parent(src) |
| 33 | + dst_parent = self.get_parent(dst) |
| 34 | + |
| 35 | + if src_parent == dst_parent: |
| 36 | + return False |
| 37 | + |
| 38 | + if self.ranks[dst_parent] >= self.ranks[src_parent]: |
| 39 | + self.set_counts[dst_parent] += self.set_counts[src_parent] |
| 40 | + self.set_counts[src_parent] = 0 |
| 41 | + self.parents[src_parent] = dst_parent |
| 42 | + if self.ranks[dst_parent] == self.ranks[src_parent]: |
| 43 | + self.ranks[dst_parent] += 1 |
| 44 | + joined_set_size = self.set_counts[dst_parent] |
| 45 | + else: |
| 46 | + self.set_counts[src_parent] += self.set_counts[dst_parent] |
| 47 | + self.set_counts[dst_parent] = 0 |
| 48 | + self.parents[dst_parent] = src_parent |
| 49 | + joined_set_size = self.set_counts[src_parent] |
| 50 | + |
| 51 | + self.max_set = max(self.max_set, joined_set_size) |
| 52 | + return True |
| 53 | + |
| 54 | + def get_parent(self, disj_set: int) -> int: |
| 55 | + """ |
| 56 | + Find the Parent of a given set |
| 57 | + >>> A = DisjointSet([1, 1, 1]) |
| 58 | + >>> A.merge(1, 2) |
| 59 | + True |
| 60 | + >>> A.get_parent(0) |
| 61 | + 0 |
| 62 | + >>> A.get_parent(1) |
| 63 | + 2 |
| 64 | + """ |
| 65 | + if self.parents[disj_set] == disj_set: |
| 66 | + return disj_set |
| 67 | + self.parents[disj_set] = self.get_parent(self.parents[disj_set]) |
| 68 | + return self.parents[disj_set] |
0 commit comments