线段树的区间更新
详情见代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#define maxn 100100
using namespace std;
int sto[maxn<<1];
int up[maxn<<1];
void Insert(int left,int right,int o)
{
up[o]=0;
if(left==right)
{
scanf("%d",&sto[o]);
return ;
}
int lso=o<<1;
int mid=(left+right)>>1;
Insert(left,mid,lso);
Insert(mid+1,right,lso|1);
sto[o]=sto[lso]+sto[lso|1];
}
void changedata(int num,int o)
{
if(up[o]!=0)
{
int lso=o<<1;
up[lso]+=up[o];
up[lso|1]+=up[o];
sto[lso]+=(num-(num>>1))*up[o];
sto[lso|1]+=(num>>1)*up[o];
up[o]=0;
}
}
int getdata(int left,int right,int o,int begin,int end,int val)
{
if(begin<=left&&right<=end)
{
if(val!=1<<28)
{
up[o]+=val;
sto[o]+=(right-left+1)*val;
}
return sto[o];
}
changedata(right-left+1,o);
int lso=o<<1;
int mid=(left+right)>>1;
int ans=0;
if(begin<=mid)ans+=getdata(left,mid,lso,begin,end,val);
if(mid<end)ans+=getdata(mid+1,right,lso|1,begin,end,val);
sto[o]=sto[lso]+sto[lso|1];
return ans;
}
int main()
{
int t,n,cnt=0;
char str[10];
scanf("%d",&t);
while(t--)
{
int x,y,z;
scanf("%d",&n);
printf("Case %d:\n",++cnt);
Insert(1,n,1);
while(true)
{
scanf("%s",str);
if(strcmp(str,"Query")==0)
{
scanf("%d%d",&x,&y);
printf("%d\n",getdata(1,n,1,x,y,1<<28));
}
else if(strcmp(str,"Add")==0)
{
scanf("%d%d",&x,&z);
int k=getdata(1,n,1,x,x,z);
}
else if(strcmp(str,"Sub")==0)
{
scanf("%d%d",&x,&z);
int k=getdata(1,n,1,x,x,0-z);//z为加上的值
}
else break;
}
}
return 0;
}