-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunion_find.py
84 lines (60 loc) · 1.95 KB
/
union_find.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from typing import Any
ValueType = Any
class UnionFindError(Exception):
pass
class DuplicateItemError(UnionFindError):
pass
class NotFoundError(UnionFindError):
pass
class UnionFind:
class Item:
def __init__(self, value: ValueType):
self._value = value
self._next = None
self._size = 1
def __lt__(self, other: "UnionFind.Item") -> bool:
return self._size < other._size
def __init__(self):
self._items = {}
def __len__(self):
return len(self._items)
def __contains__(self, value: ValueType) -> bool:
return value in self._items
def add_new(self, value: ValueType):
if value in self:
raise DuplicateItemError
new_item = self.Item(value)
self._items[value] = new_item
def union(self, a: ValueType, b: ValueType) -> bool:
"""
Returns whether a new union was created.
"""
if a not in self:
self.add_new(a)
if b not in self:
self.add_new(b)
a_leader = self._find_leader(a)
b_leader = self._find_leader(b)
if a_leader is b_leader:
return False
# union by rank
if a_leader < b_leader:
a_leader._next = b_leader
b_leader._size += a_leader._size
else:
b_leader._next = a_leader
a_leader._size += b_leader._size
return True
def same_partition(self, a: ValueType, b: ValueType) -> bool:
return self._find_leader(a) is self._find_leader(b)
def _find_leader(self, value: ValueType):
if value not in self:
raise NotFoundError
ancestors = [self._items[value]]
while ancestors[-1]._next is not None:
ancestors.append(ancestors[-1]._next)
leader = ancestors.pop()
# path compression
for node in ancestors:
node._next = leader
return leader