区间求和,以前线段树写的,用树状数组写了一下,还是树状数组好用啊。。T_T
而且树状数组的时间好像比线段树要快,编程复杂度更低。。
/********************** * author:crazy_石头 * Pro:HDU 1166 * algorithm:树状数组求区间和 * Time:31ms * Judge Status:Accepted ***********************/ #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <queue> #include <vector> using namespace std; #define rep(i,h,n) for(int i=(h);i<=(n);i++) #define ms(a,b) memset((a),(b),sizeof(a)) #define eps 1e-6 #define INF 1<<29 #define LL __int64 const int maxn=50000+5; const int maxm=200+10; int C[maxn],a[maxn];//树状数组为C数组,相当于一个前缀和数组; int n; inline int lowbit(int x) { return x&-x; } inline void update(int x,int y) { while(x<=n) { C[x]+=y; x+=lowbit(x); } } inline int getsum(int x) { int res=0; while(x>0) { res+=C[x]; x-=lowbit(x); } return res; } int main() { int test,t=1,num; char str[maxn]; scanf("%d",&test); while(test--) { printf("Case %d:\n",t++); scanf("%d",&n); ms(C,0); rep(i,1,n) { scanf("%d",&num); update(i,num); } scanf("%s",str); while(str[0]!='E') { int x,y; scanf("%d%d",&x,&y); if(str[0]=='A') update(x,y); else if(str[0]=='S') update(x,-y); else printf("%d\n",getsum(y)-getsum(x-1)); scanf("%s",str); } } return 0; }