File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree 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"
53
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
1011 i += i & - i
1112
1213 # 返回闭区间 [1, i] 的元素和
13- def sum (self , i : int ) -> int :
14+ def pre (self , i : int ) -> int :
1415 res = 0
1516 while i > 0 :
16- res += self .tree [i ]
17+ res += self .f [i ]
1718 i &= i - 1
1819 return res
1920
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+
2327
2428n = II ()
2529a = LII ()
2630num2idx = {}
27- for i , x in enumerate (sorted (a ), start = 1 ):
31+ for i , x in enumerate (sorted (a ), 1 ):
2832 num2idx [x ] = i
29- ft = FenwickTree (n )
33+ f = Fenwick (n )
You can’t perform that action at this time.
0 commit comments