@@ -16,7 +16,7 @@ class MaxFenwickTree:
16
16
20
17
17
>>> ft.update(4, 10)
18
18
>>> ft.query(2, 5)
19
- 10
19
+ 20
20
20
>>> ft.query(1, 5)
21
21
20
22
22
>>> ft.update(2, 0)
@@ -26,6 +26,14 @@ class MaxFenwickTree:
26
26
>>> ft.update(255, 30)
27
27
>>> ft.query(0, 10000)
28
28
30
29
+ >>> ft = MaxFenwickTree(6)
30
+ >>> ft.update(5, 1)
31
+ >>> ft.query(5, 6)
32
+ 1
33
+ >>> ft = MaxFenwickTree(6)
34
+ >>> ft.update(0, 1000)
35
+ >>> ft.query(0, 1)
36
+ 1000
29
37
"""
30
38
31
39
def __init__ (self , size : int ) -> None :
@@ -47,14 +55,14 @@ def get_next(index: int) -> int:
47
55
"""
48
56
Get next index in O(1)
49
57
"""
50
- return index + (index & - index )
58
+ return index | (index + 1 )
51
59
52
60
@staticmethod
53
61
def get_prev (index : int ) -> int :
54
62
"""
55
63
Get previous index in O(1)
56
64
"""
57
- return index - (index & - index )
65
+ return ( index & (index + 1 )) - 1
58
66
59
67
def update (self , index : int , value : int ) -> None :
60
68
"""
@@ -69,7 +77,11 @@ def update(self, index: int, value: int) -> None:
69
77
"""
70
78
self .arr [index ] = value
71
79
while index < self .size :
72
- self .tree [index ] = max (value , self .query (self .get_prev (index ), index ))
80
+ current_left_border = self .get_prev (index ) + 1
81
+ if current_left_border == index :
82
+ self .tree [index ] = value
83
+ else :
84
+ self .tree [index ] = max (value , current_left_border , index )
73
85
index = self .get_next (index )
74
86
75
87
def query (self , left : int , right : int ) -> int :
@@ -85,9 +97,9 @@ def query(self, left: int, right: int) -> int:
85
97
"""
86
98
right -= 1 # Because of right is exclusive
87
99
result = 0
88
- while left < right :
100
+ while left <= right :
89
101
current_left = self .get_prev (right )
90
- if left < current_left :
102
+ if left <= current_left :
91
103
result = max (result , self .tree [right ])
92
104
right = current_left
93
105
else :
0 commit comments