Contents
  • 通过lowbit实现log级的移动
  • 单点更新
  • 区间更新
  • 区间求和

  • 补:树状数组能解决的问题线段树也能解决,但线段树能解决的问题,树状数组不一定能解决

  • 1 对于区间求和的问题一般利用树状数组比线段树来的方便
  • 2 树状数组建立就是在输入数据的时候做n次的update()。

树状数组

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

#include <cstdio>
#include <cstring>
#include <cstdlib>

int tree[100], a[100], n;//树状数组tree要从下标1开始,不然lowbit算的值是错的

int lowbit(int k)
{

return k & -k;
}

void update(int index, int val)
{

while(index <= n)
{
tree[index] += val;
index += lowbit(index);
}
}

int sum(int index)
{

int ans = 0;
while(index > 0)
{
ans += tree[index];
index -= lowbit(index);
}
return ans;
}

int main()
{

int m, left, right, i;
char ch[3];
while(scanf("%d%d", &n, &m) != EOF)
{
memset(tree, 0, sizeof(tree));
for(i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
update(i, a[i]);
}
while(m--)
{
scanf("%s%d%d", &ch, &left, &right);
if(ch[0] == 'Q')
printf("%d\n", sum(right) - sum(left - 1));
else
{
update(left, right - a[left]); //update()函数参数val代表的不是要换的数,而是要加上的数据
a[left] = right; //所以要表达要换某个数时要先减去原数据转换为要加的数据
}
}
}
return 0;
}
Contents