首页 > 代码库 > HDU 1166(树状数组)

HDU 1166(树状数组)

用树状数组把HDU1166再写了一次  感觉树状数组简洁

 1 #include <cstdio> 2 #include <iostream> 3 #include <string.h> 4 using namespace std; 5 int c[50002],lv[50002],n; 6 int lowbit(int x){return x&(-x);} 7 int sum(int b){ 8     int sum=0; 9     while(b>0){10         sum+=c[b];11         b-=lowbit(b);12     }13     return sum;14 }15 void add(int x,int val){16     while(x<=n){17         c[x]+=val;18         x+=lowbit(x);19     }20 }21 void init(){22     for(int i=1;i<=n;i++){23         add(i,lv[i]);24     }25 }26 int main(){27     int t,a,b;28     scanf("%d",&t);29     for(int i=1;i<=t;i++){30         scanf("%d",&n);31        // memset(lv,0,sizeof(lv));32        // memset(c,0,sizeof(c));33         for(int j=1;j<=n;j++){34             scanf("%d",&lv[j]);35             c[j]=0;36         }37         init();38         char s[8];39         printf("Case %d:\n",i);40         while(scanf("%s",s)){41             if(s[0]==E)break;42             scanf("%d%d",&a,&b);43             switch (s[0]){44                 case A:add(a,b);break;45                 case S:add(a,-b);break;46                 case Q:printf("%d\n",sum(b)-sum(a-1));47             }48         }49     }50     return 0;51 }