首页 > 代码库 > [模板]树状数组

[模板]树状数组

OJ题号:洛谷P3374

 1 #include<cstdio> 2 #include<cstring> 3 #define maxn 500000 4 int n,m; 5 struct BIT { 6     int val[maxn]; 7     BIT() { 8         memset(val,0,sizeof val); 9     }10     int lowbit(int x) {11         return x&-x;12     }13     void modify(int p,const int x) {14         while(p<=n) {15             val[p]+=x;16             p+=lowbit(p);17         }18     }19     int query(int p) {20         int ans=0;21         while(p) {22             ans+=val[p];23             p-=lowbit(p);24         }25         return ans;26     }27 };28 BIT tree;29 int main() {30     scanf("%d%d",&n,&m);31     for(int i=1;i<=n;i++) {32         int x;33         scanf("%d",&x);34         tree.modify(i,x);35     }36     while(m--) {37         int op,x,y;38         scanf("%d%d%d",&op,&x,&y);39         if(op==1) {40             tree.modify(x,y);41         }42         else {43             printf("%d\n",tree.query(y)-tree.query(x-1));44         }45     }46     return 0;47 }

 

[模板]树状数组