树状数组和线段树

树状数组模板

 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
n,m = map(int,input().split())
t = list(map(int,input().split()))
c = [0] * (n+1)

def lowbit(x):
    return x & (-x)

def add(idx,d):
    while idx <= n:
        c[idx] += d
        idx += lowbit(idx)

    
def query(idx):
    res = 0
    while idx > 0:
        res += c[idx]
        idx -= lowbit(idx)
    return res

def rs(l,r):
    return query(r) - query(l)


for i,v in enumerate(t, start = 1):
    add(i,v)

for i in range(m):
    k,a,b = map(int,input().split())
    if k == 0:
        print(rs(a-1,b)) #注意需要包含第a个元素
    else:
        add(a,b)
操作 普通数组 前缀和数组 树状数组
单点更新 O(1) O(n) O(log n)
区间查询 O(n) O(1) O(log n)
Built with Hugo
Theme Stack designed by Jimmy