fenwick树

关键可以在$O(log n)$时间内求得数组任意前缀和,同时支持动态单点值的修改
这个数可以用一个一维数组表示(1~n), 第i项表示前i项的和。

1
2
3
4
5
6
7
8
9
10
11
12
13
fenwick = [0]*(max_len+1)
def (x):
return x&(-x)
def add(pos, value):
while pos <= max_len:
fenwick[pos] += value
pos += lowbit(pos)
def sum(pos):
res = 0
while pos != 0:
res += fenwick[pos]
pos -= lowbit(pos)
return res

典型应用:求逆序对数量