-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdisjoint.py
47 lines (39 loc) · 1.39 KB
/
disjoint.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
from disjoint_set import DisjointSet
class DisjointSetExtra():
def __init__(self):
self.ds = DisjointSet()
self.ds_counter = dict()
# one of the two nodes doesnot exist
def add(self,node1,node2):
if node1 in self.ds:
self.union(node2,node1)
self.ds_counter[self.find(node1)] += 1
elif node2 in self.ds:
self.union(node1,node2)
self.ds_counter[self.find(node2)] += 1
else:
self.union(node2,node1)
self.ds_counter[self.find(node2)] = 2
def find(self,node):
return self.ds.find(node)
def count(self,node):
return self.ds_counter[self.find(node)]
# added
def connect(self,node1,node2):
name1 = self.find(node1)
name2 = self.find(node2)
if self.ds_counter[name1] < self.ds_counter[name2]:
self.ds_counter[name2] = int(self.ds_counter[name2]+self.ds_counter[name1])
self.union(node1,node2)
del self.ds_counter[name1]
else:
self.ds_counter[name1] = self.ds_counter[name2]+self.ds_counter[name1]
self.union(node2,node1)
del self.ds_counter[name2]
# added
def exists(self,node):
return node in self.ds
def union(self,node1,node2):
self.ds.union(node1,node2)
def connected(self,node1,node2):
return self.ds.connected(node1,node2)