hdu1166 敌兵布阵(单点更新)

转载请注明出处忆梦http://blog.csdn.net/yimeng2013/article/details/17187379


题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166

线段树功能:update:单点增减 query:区间求和 

跟着NotOnlySuccess大牛学线段树


#include<cstdio>
#define lson l, m, rt << 1
#define rson m+1, r, rt << 1 | 1
#define maxn 55555
int sum[maxn << 2];

void PushUP(int rt)
{
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void build(int l, int r, int rt)
{
    if(l == r)
    {
        scanf("%d", &sum[rt]);
        return;
    }

    int m = (l + r) >> 1;
    build(lson);
    build(rson);
    PushUP(rt);
}

void update(int p, int add, int l, int r,  int rt)
{
    if(l == r)
    {
        sum[rt] += add;
        return ;
    }

    int m = (l + r) >> 1;
    if(p <= m) update(p, add, lson);
    else      update(p, add, rson);
    PushUP(rt);
}
int query(int L, int R, int l, int r, int rt)
{
    if(L <= l && r <= R)
    {
        return sum[rt];
    }

    int ret = 0;
    int m = (l + r) >> 1;
    if(L <= m) ret += query(L, R, lson);
    if(R > m)  ret += query(L, R, rson);
    return ret;
}
int main ()
{
    int T, n;
    scanf("%d", &T);
    for(int t = 1; t <= T; t++)
    {
        printf("Case %d:\n", t);

        scanf("%d", &n);
        build(1, n, 1);

        char op[10];
        while(scanf("%s", op))
        {
            if(op[0] == 'E') break;

            int a, b;
            scanf("%d %d", &a, &b);
            if(op[0] == 'Q')       printf("%d\n",query(a, b, 1, n, 1));
            else if(op[0] == 'A') update(a, b, 1, n, 1);
            else if(op[0] == 'S') update(a, -b, 1, n, 1);
        }
    }
    return 0;
}










你可能感兴趣的:(hdu1166 敌兵布阵(单点更新))