-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisjintv1.py
104 lines (70 loc) · 1.76 KB
/
disjintv1.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import bisect
class DisjIntvs():
def __init__(self, intvs=[]):
self.intvs = []
if intvs:
for a, b in intvs:
self.add(a, b)
def __str__(self):
n = len(self.intvs)
ret = [[self.intvs[i], self.intvs[i+1]] for i in range(0, n, 2)]
return str(ret)
def add(self, a, b):
print("+", a, b)
if a == b: # invalid interval, do nothing
return
if not self.intvs: # no intvs stored
self.intvs = [a, b]
#print(self.intvs)
print(self.__str__())
return
# find the lower and upper index
i = bisect.bisect_left(self.intvs, a)
j = bisect.bisect_right(self.intvs, b)
temp = []
if i % 2 == 0:
temp.append(a)
if j % 2 == 0:
temp.append(b)
self.intvs[i:j] = temp
print(self.__str__())
return
def remove(self, a, b):
print("-", a, b)
if a == b: # invalid interval, do nothing
return
if not self.intvs: # no intv stored
#print(self.intvs)
print(self.__str__())
return # do nothing
# find the lower and upper index
i = bisect.bisect_left(self.intvs, a)
j = bisect.bisect_right(self.intvs, b)
temp = []
if i % 2 == 1:
temp.append(a)
if j % 2 == 1:
temp.append(b)
self.intvs[i:j] = temp
print(self.__str__())
return
class Operator():
def __init__(self, intvs=[], acts=[]):
self.intvs = DisjIntvs(intvs) # maintian a set of intervals
self.acts = acts # maintian a set of actions
def run(self):
for com, a, b in self.acts:
if com: # com=1: add
self.intvs.add(a, b)
else: # com=0: remove
self.intvs.remove(a, b)
def result(self):
#print(self.intvs)
return self.intvs.__str__()
# main section
if __name__ == '__main__':
A = [[1,1,5],[1,6,8],[1,3,5],[1,5,6]]
#A = [[1,1,8],[0,3,9]]
#A = [[1,2,5],[0,3,4]]
opt = Operator(acts=A)
opt.run()