首页 > 代码库 > 树状数组

树状数组

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

int tree[50005],n;

inline int lowbit(int x)
{
    return x & (-x);
}

void update(int pos,int x)
{
    while(pos <= n)
    {
        tree[pos] += x;
        pos += lowbit(pos);
    }
}

int getsum(int pos)
{
    int sum = 0;
    while(pos > 0)
    {
        sum += tree[pos];
        pos -= lowbit(pos);
    }
    return sum;
}

int main()
{
    int T;
    scanf("%d",&T);
    for(int z = 1;z <= T;z++)
    {
        memset(tree,0,sizeof(tree));
        printf("Case %d:\n",z);
        scanf("%d",&n);
        int temp;
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&temp);
            update(i,temp);
        }
        char s[10];
        while(scanf("%s",s) && s[0] != E)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            if(s[0] == A) update(a,b);
            else if(s[0] == S)    update(a,-b);
            else    printf("%d\n",getsum(b)-getsum(a-1));
        }
    }
    return 0;
}
//HDU1166

 

树状数组