树状数组

这里有比较易懂的关于树状数组的博客,可以看看,我就不多解释了。。。。。

http://blog.csdn.net/moep0/article/details/52770728

http://blog.csdn.net/fsahfgsadhsakndas/article/details/52650026

https://www.cnblogs.com/lcf-2000/p/5866170.html

 

献上模版

 1 //单点修改,区间查询
 2 #include
 3 #include
 4 #include
 5 #include
 6 #include
 7 #include
 8 #include
 9 #define ll long long
10 using namespace std;
11 int f[100001],n,m;
12 int lowbit(int x){return x&(-x);}
13 void udata(int x,int v){
14     for(int i=x;i<=n;i+=lowbit(i))f[i]+=v;
15 }
16 int count(int x){
17     int num=0;
18     for(int i=x;i>0;i-=lowbit(i))num+=f[i];
19     return num;
20 }
21 int main(){
22     scanf("%d",&n);
23     for(int i=1;i<=n;i++){
24         int x;
25         scanf("%d",&x);
26         udata(i,x);        
27     }
28     scanf("%d",&m);
29     for(int i=1;i<=m;i++){
30         int k,x,y;
31         scanf("%d%d%d",&k,&x,&y);
32         if(k==1){
33             udata(x,y);
34         }
35         else{
36             printf("%d\n",count(y)-count(x-1));
37         }
38     }
39     return 0;
40 }
View Code
 1 //区间修改,单点查询
 2 #include
 3 #include
 4 #include
 5 #include
 6 #include
 7 #include
 8 #include
 9 #define ll long long
10 using namespace std;
11 int f[100001],n,m,a[100001];
12 int lowbit(int x){return x&(-x);}
13 void udata(int x,int v){
14     for(int i=x;i<=n;i+=lowbit(i))f[i]+=v;
15 }
16 int count(int x){
17     int num=0;
18     for(int i=x;i>0;i-=lowbit(i))num+=f[i];
19     return num;
20 }
21 int main(){
22     scanf("%d",&n);
23     for(int i=1;i<=n;i++){
24         scanf("%d",&a[i]);
25         //f数组是一个查分数组,不能在这里直接udata(i,a[i]);
26         //或者写成udata(i,x),udata(i+1,-a[i]);
27     }
28     scanf("%d",&m);
29     for(int i=1;i<=m;i++){
30         int k,x,y,v;
31         scanf("%d%d",&k,&x);
32         if(k==1){
33             scanf("%d%d",&y,&v);
34             udata(x,v);
35             udata(y+1,-v);
36         }
37         else{
38             printf("%d\n",count(x)+a[x]);
39         }
40     }
41     return 0;
42 }
View Code

 

转载于:https://www.cnblogs.com/wzq--boke/p/8397425.html

你可能感兴趣的:(树状数组)