File tree 1 file changed +19
-15
lines changed
1 file changed +19
-15
lines changed Original file line number Diff line number Diff line change 1
- class FenwickTree :
2
- def __init__ (self , n ):
3
- self .size = n
4
- self .tree = [0 ] * (n + 1 )
1
+ class Fenwick :
2
+ __slots__ = "f"
5
3
6
- # 将下标 i 上的数加一
7
- def inc (self , i : int ) -> None :
8
- while i < len (self .tree ):
9
- self .tree [i ] += 1
4
+ def __init__ (self , n : int ):
5
+ self .f = [0 ] * (n + 1 )
6
+
7
+ # 将下标i处值增加val
8
+ def update (self , i : int , val : int ) -> None :
9
+ while i < len (self .f ):
10
+ self .f [i ] += val
10
11
i += i & - i
11
12
12
13
# 返回闭区间 [1, i] 的元素和
13
- def sum (self , i : int ) -> int :
14
+ def pre (self , i : int ) -> int :
14
15
res = 0
15
16
while i > 0 :
16
- res += self .tree [i ]
17
+ res += self .f [i ]
17
18
i &= i - 1
18
19
return res
19
20
20
- # 返回闭区间 [left, right] 的元素和
21
- def query (self , left : int , right : int ) -> int :
22
- return self .sum (right ) - self .sum (left - 1 )
21
+ # 返回闭区间 [l, r] 的元素和
22
+ def query (self , l : int , r : int ) -> int :
23
+ if r < l :
24
+ return 0
25
+ return self .pre (r ) - self .pre (l - 1 )
26
+
23
27
24
28
n = II ()
25
29
a = LII ()
26
30
num2idx = {}
27
- for i , x in enumerate (sorted (a ), start = 1 ):
31
+ for i , x in enumerate (sorted (a ), 1 ):
28
32
num2idx [x ] = i
29
- ft = FenwickTree (n )
33
+ f = Fenwick (n )
You can’t perform that action at this time.
0 commit comments