题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166
BIT简单应用,加减,求和操作。 自己没有注意每次数组归零,果断傻逼的交了好多次,WA啊...... Orz
代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <math.h> 4 #include <algorithm> 5 #include <iostream> 6 #include <ctype.h> 7 #include <iomanip> 8 #include <queue> 9 #include <stdlib.h> 10 using namespace std; 11 12 int s[50005]; 13 int t,n,m,p,i,j; 14 15 int lowbit(int x) 16 { 17 return x&(-x); 18 } 19 20 void add(int x, int d){ 21 while (x <= n){ 22 s[x] += d; 23 x += lowbit(x); 24 } 25 } 26 27 int sum(int x){ 28 int ans = 0; 29 while (x > 0){ 30 ans += s[x]; 31 x -= lowbit(x); 32 } 33 return ans; 34 } 35 36 int main() 37 { 38 39 scanf("%d",&t); 40 for(m=1; m<=t;m++){ 41 printf("Case %d: ",m); 42 scanf("%d",&n); 43 memset(s,0,sizeof(s)); 44 for (i = 1; i <= n; i++){ 45 scanf("%d", &p); 46 add(i, p); 47 } 48 char str[10]; 49 50 while(~scanf("%s",&str)){ 51 int x,y; 52 if(strcmp(str,"Add")==0){ 53 scanf("%d%d",&x,&y); 54 add(x,y); 55 } 56 else if(strcmp(str,"Sub")==0){ 57 scanf("%d%d",&x,&y); 58 add(x,-y); 59 } 60 else if(strcmp(str,"Query")==0){ 61 scanf("%d %d",&x,&y); 62 printf("%d ",sum(y)-sum(x-1)); 63 } 64 if(strcmp(str,"End")==0){ 65 break; 66 } 67 } 68 } 69 }