树状数组

来源:互联网 发布:盐和避难所 mac 中文 编辑:程序博客网 时间:2024/05/18 13:24

代码包含树状数组:建立,更新,加减运算,求和。和线段树类似,但比线段树简单,而且:x&(-x)代表2的k次幂,也就是lowbit(X),就是加上x的从最低位1开始的数,树状数组的分组有一个特点:分的区间不会交叉。加和是就要x-=x&(-x)

更新和加减就要x+=x&(-x)

#include<iostream>#include<cstring>#include<cstdio>const int maxn=1000;using namespace std;int c[maxn];int a[maxn];int getsum(int x){    int sum=0;    while(x>0)    {        sum+=c[x];        x-=x&(-x);    }    return sum;}void add(int x,int v){    a[x]+=v;    while(x<=maxn)    {        c[x]+=v;        x+=x&(-x);    }}void change(int x,int v){    int temp=v-a[x];    a[x]=v;    while(x<=maxn)    {        c[x]+=temp;        x+=x&(-x);    }}int main(){    add(12,12);    change(11,2);    change(8,8);    cout<<getsum(12)<<endl;    add (10,10);    cout<<getsum(12)<<endl;    change (10,5);    cout<<getsum(12)<<endl;    return 0;}


0 0
原创粉丝点击