LouZhang

导航

hdu_1166,树状数组的学习

至于数状数组是怎么来的,这个得找资料了。。。也不知道怎么上传。。所以我也不讲了

可以参考这个http://blog.csdn.net/cambridgeacm/article/details/7771782

 

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

这题是很经典的题,最开始是学线段树的时候做的,这次学树状数组,又做了一遍

#include<cstdio>
#include<cstring>
const int maxn = 50000 + 10;
int a[maxn], c[maxn];
int n;
inline int lowbit(int x){
    return x&(-x);
}
inline void update(int pos, int x){
    while(pos <= n){
        c[pos] += x;
        pos += lowbit(pos);
    }
}
inline int query(int end){
    int sum = 0;
    while(end > 0){
        sum += c[end];
        end -= lowbit(end);
    }
    return sum;
}
int main(){
    int tcase;
    scanf("%d", &tcase);
    int z = 1;
    while(tcase --){
        scanf("%d", &n);
        memset(a, 0, sizeof a);
        memset(c, 0, sizeof c);
        for(int i = 1; i <= n;i ++){
            scanf("%d", a + i);
            update(i, a[i]);
        }
        printf("Case %d:\n", z++);
        char op[10];
        while(scanf("%s", op) && op[0] != 'E'){
            int i, j;
            scanf("%d%d", &i, &j);
            switch(op[0]){
                case 'Q':
                    printf("%d\n", query(j) - query(i - 1));
                    break;
                case 'A':
                    update(i, j);
                    a[i] += j;
                    break;
                case 'S':
                    update(i, -j);
                    a[i] -= j;
            }
        }
    }
    return 0;
}

posted on 2012-08-03 12:26  louzhang_swk  阅读(186)  评论(0编辑  收藏  举报