树状数组单点更新和区间查询

这里是最基本的操作。

单操作时间复杂度O(logN),空间复杂度O(N).

 1 #include <fstream>
 2 #include <iostream>
 3 #include <cstdio>
 4 
 5 using namespace std;
 6 
 7 int n,m;
 8 int a[100002],tree[100002];
 9 
10 void build();//建树状数组
11 int read(int pos);//求 sum[1,pos]的答案
12 void update(int pos,int val);//把a[pos]加上v
13 
14 int main(){
15     //freopen("D:\\input.in","r",stdin);
16     //freopen("D:\\output.out","w",stdout);
17     int bo,t1,t2;
18     scanf("%d %d",&n,&m);
19     for(int i=1;i<=n;i++)
20         scanf("%d",&a[i]);
21     build();
22     for(int i=1;i<=m;i++){
23         scanf("%d%d%d",&bo,&t1,&t2);
24         if(bo)
25             update(t1,t2);
26         else
27             printf("%d\n",read(t2)-read(t1-1));
28     }
29     return 0;
30 }
31 void build(){
32     tree[0]=0;
33     for(int i=1;i<=n;i++){
34         tree[i]=a[i];
35         for(int j=i-1;j>i-(i&(-i));j=j-(j&(-j)))
36             tree[i]+=tree[j];
37     }
38 }
39 int read(int pos){
40     int ans=0;
41     while(pos>0){
42         ans+=tree[pos];
43         pos-=pos&(-pos);
44     }
45     return ans;
46 }
47 void update(int pos,int val){
48     while(pos<=n){
49         tree[pos]+=val;
50         pos+=pos&(-pos);
51     }
52 }

 

posted @ 2014-12-04 23:36  jiu~  阅读(253)  评论(0编辑  收藏  举报