HDU_1166_树状数组

http://acm.hdu.edu.cn/showproblem.php?pid=1166

树状数组入门题。

#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:
",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
",getsum(b)-getsum(a-1));
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhurb/p/5931617.html