【樹狀陣列 單點修改,區間求值】hdu 1166 敵兵佈陣

CN_swords發表於2017-08-15

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

#include <bits/stdc++.h>
using namespace std;

const int N = 5e4+5;
char s[10];
int tree[N],n;
void add(int x,int num){
    while(x<=n){
        tree[x]+=num;
        x += x&(-x);
    }
}
int getpre(int x){
    int ans = 0;
    while(x){
        ans+=tree[x];
        x -= x&(-x);
    }
    return ans;
}
int query(int x,int y){
    return getpre(y)-getpre(x-1);
}

int main(){
    int T,a;
    scanf("%d",&T);
    for(int cas=1; cas<=T; cas++){
        memset(tree,0,sizeof(tree));
        scanf("%d",&n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d",&a);
            add(i,a);
        }
        printf("Case %d:\n",cas);
        int x,y;
        while(~scanf("%s",s)){
            if(strcmp(s,"End")==0)
                break;
            scanf("%d%d",&x,&y);
            if(strcmp(s,"Add")==0)
                add(x,y);
            else if(strcmp(s,"Sub")==0)
                add(x,-y);
            else
                printf("%d\n",query(x,y));
        }
    }
    return 0;
}


相關文章