1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 EndSample Output
Case 1: 6 33 59
思路:树状数组模版题。可以用线段树,写起来有点麻烦,树状数组写起来简单。
#include
using namespace std;
const int MAX=1e5;
int b[MAX],c[MAX],n;
int lowbit(int x){return x&(-x);}
int sum(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
void add(int x,int y)
{
while(x<=n)
{
c[x]+=y;
x+=lowbit(x);
}
}
int main()
{
int T,cas=1;cin>>T;
while(T--)
{
cin>>n;
memset(c,0,sizeof c);
for(int i=1;i<=n;i++)scanf("%d",&b[i]);
for(int i=1;i<=n;i++)
{
for(int j=i-lowbit(i)+1;j<=i;j++)c[i]+=b[j];
}
printf("Case %d:\n",cas++);
char op[10];
while(scanf("%s",op)&&strcmp(op,"End")!=0)
{
int x,y;
scanf("%d%d",&x,&y);
if(strcmp(op,"Query")==0)
{
printf("%d\n",sum(y)-sum(x-1));
}
else if(strcmp(op,"Add")==0)add(x,y);
else if(strcmp(op,"Sub")==0)add(x,-y);
}
}
return 0;
}