https://en.wikipedia.org/wiki/Disjoint-set_data_structure The union-find is a disjoint-set data structure You can merge two sets and tell if one set belongs to another one. It's used on the Kruskal Algorithm (https://en.wikipedia.org/wiki/Kruskal%27s_algorithm) The e
| 1 | class UnionFind(): |
| 2 | """ |
| 3 | https://en.wikipedia.org/wiki/Disjoint-set_data_structure |
| 4 | |
| 5 | The union-find is a disjoint-set data structure |
| 6 | |
| 7 | You can merge two sets and tell if one set belongs to |
| 8 | another one. |
| 9 | |
| 10 | It's used on the Kruskal Algorithm |
| 11 | (https://en.wikipedia.org/wiki/Kruskal%27s_algorithm) |
| 12 | |
| 13 | The elements are in range [0, size] |
| 14 | """ |
| 15 | def __init__(self, size): |
| 16 | if size <= 0: |
| 17 | raise ValueError("size should be greater than 0") |
| 18 | |
| 19 | self.size = size |
| 20 | |
| 21 | # The below plus 1 is because we are using elements |
| 22 | # in range [0, size]. It makes more sense. |
| 23 | |
| 24 | # Every set begins with only itself |
| 25 | self.root = [i for i in range(size+1)] |
| 26 | |
| 27 | # This is used for heuristic union by rank |
| 28 | self.weight = [0 for i in range(size+1)] |
| 29 | |
| 30 | def union(self, u, v): |
| 31 | """ |
| 32 | Union of the sets u and v. |
| 33 | Complexity: log(n). |
| 34 | Amortized complexity: < 5 (it's very fast). |
| 35 | """ |
| 36 | |
| 37 | self._validate_element_range(u, "u") |
| 38 | self._validate_element_range(v, "v") |
| 39 | |
| 40 | if u == v: |
| 41 | return |
| 42 | |
| 43 | # Using union by rank will guarantee the |
| 44 | # log(n) complexity |
| 45 | rootu = self._root(u) |
| 46 | rootv = self._root(v) |
| 47 | weight_u = self.weight[rootu] |
| 48 | weight_v = self.weight[rootv] |
| 49 | if weight_u >= weight_v: |
| 50 | self.root[rootv] = rootu |
| 51 | if weight_u == weight_v: |
| 52 | self.weight[rootu] += 1 |
| 53 | else: |
| 54 | self.root[rootu] = rootv |
| 55 | |
| 56 | def same_set(self, u, v): |
| 57 | """ |
| 58 | Return true if the elements u and v belongs to |
| 59 | the same set |
| 60 | """ |
no outgoing calls