| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
class UnionFind(object): |
| 7 |
def __init__(self, info_factory=None): |
| 8 |
self.link_to_parent = {} |
| 9 |
self.weight = {} |
| 10 |
self.info_factory = info_factory |
| 11 |
self.root_info = {} |
| 12 |
|
| 13 |
|
| 14 |
def __getitem__(self, obj): |
| 15 |
if obj not in self.link_to_parent: |
| 16 |
raise KeyError(obj) |
| 17 |
|
| 18 |
ignore, rep, info = self.find(obj) |
| 19 |
|
| 20 |
return info |
| 21 |
|
| 22 |
def __contains__(self, obj): |
| 23 |
return obj in self.link_to_parent |
| 24 |
|
| 25 |
def __iter__(self): |
| 26 |
return iter(self.link_to_parent) |
| 27 |
|
| 28 |
def keys(self): |
| 29 |
return self.link_to_parent.keys() |
| 30 |
|
| 31 |
def infos(self): |
| 32 |
return self.root_info.values() |
| 33 |
|
| 34 |
def find_rep(self, obj): |
| 35 |
try: |
| 36 |
|
| 37 |
parent = self.link_to_parent[obj] |
| 38 |
self.root_info[parent] |
| 39 |
return parent |
| 40 |
except KeyError: |
| 41 |
|
| 42 |
ignore, rep, info = self.find(obj) |
| 43 |
return rep |
| 44 |
|
| 45 |
def find(self, obj): |
| 46 |
if obj not in self.link_to_parent: |
| 47 |
if self.info_factory: |
| 48 |
info = self.info_factory(obj) |
| 49 |
else: |
| 50 |
info = None |
| 51 |
self.root_info[obj] = info |
| 52 |
self.weight[obj] = 1 |
| 53 |
self.link_to_parent[obj] = obj |
| 54 |
return True, obj, info |
| 55 |
|
| 56 |
to_root = [obj] |
| 57 |
parent = self.link_to_parent[obj] |
| 58 |
while parent is not to_root[-1]: |
| 59 |
to_root.append(parent) |
| 60 |
parent = self.link_to_parent[parent] |
| 61 |
|
| 62 |
for obj in to_root: |
| 63 |
self.link_to_parent[obj] = parent |
| 64 |
|
| 65 |
return False, parent, self.root_info[parent] |
| 66 |
|
| 67 |
def union(self, obj1, obj2): |
| 68 |
|
| 69 |
new1, rep1, info1 = self.find(obj1) |
| 70 |
new2, rep2, info2 = self.find(obj2) |
| 71 |
|
| 72 |
if rep1 is rep2: |
| 73 |
return new1 or new2, rep1, info1 |
| 74 |
|
| 75 |
if info1 is not None: |
| 76 |
info1.absorb(info2) |
| 77 |
|
| 78 |
w1 = self.weight[rep1] |
| 79 |
w2 = self.weight[rep2] |
| 80 |
w = w1 + w2 |
| 81 |
if w1 < w2: |
| 82 |
rep1, rep2 = rep2, rep1 |
| 83 |
|
| 84 |
self.link_to_parent[rep2] = rep1 |
| 85 |
del self.weight[rep2] |
| 86 |
del self.root_info[rep2] |
| 87 |
|
| 88 |
self.weight[rep1] = w |
| 89 |
self.root_info[rep1] = info1 |
| 90 |
|
| 91 |
return True, rep1, info1 |
| 92 |
|
| 93 |
def union_list(self, objlist): |
| 94 |
if len(objlist) == 0: |
| 95 |
return |
| 96 |
obj0 = objlist[0] |
| 97 |
self.find(obj0) |
| 98 |
for obj1 in objlist[1:]: |
| 99 |
self.union(obj0, obj1) |