-
Notifications
You must be signed in to change notification settings - Fork 161
/
disjoint_set.py
65 lines (61 loc) · 1.54 KB
/
disjoint_set.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
class DisjointSet(object):
def __init__(self):
self.leader = {} # maps a member to the group's leader
self.group = {} # maps a group leader to the group (which is a set)
def add(self, a, b):
leadera = self.leader.get(a)
leaderb = self.leader.get(b)
if leadera is not None:
if leaderb is not None:
if leadera == leaderb: return # nothing to do
groupa = self.group[leadera]
groupb = self.group[leaderb]
if len(groupa) < len(groupb):
a, leadera, groupa, b, leaderb, groupb = b, leaderb, groupb, a, leadera, groupa
groupa |= groupb
del self.group[leaderb]
for k in groupb:
self.leader[k] = leadera
else:
self.group[leadera].add(b)
self.leader[b] = leadera
else:
if leaderb is not None:
self.group[leaderb].add(a)
self.leader[a] = leaderb
else:
self.leader[a] = self.leader[b] = a
self.group[a] = set([a, b])
mylist="""
specimen|3
sample
prototype
example
sample|3
prototype
example
specimen
prototype|3
example
specimen
sample
example|3
specimen
sample
prototype
prototype|1
illustration
specimen|1
cat
happy|2
glad
cheerful
"""
ds = DisjointSet()
for line in mylist.strip().splitlines():
if '|' in line:
node, _ = line.split('|')
else:
ds.add(node, line)
for _,g in ds.group.items():
print g