题目链接:点击打开链接
代码:自己
//单点更新 区间查询
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define MAXN 50005
int setTree[MAXN<<2];
void PushUp(int root){
setTree[root]=setTree[root<<1]+setTree[root<<1|1];
return;
}
void Build(int L,int R,int root){
if(L==R){
scanf("%d",&setTree[root]);
return;
}
int M=(L+R)>>1;
Build(L,M,root<<1);
Build(M+1,R,root<<1|1);
PushUp(root);
}
void Update(int p,int key,int L,int R,int root){
if(L==R){
setTree[root]+=key;
return;
}
int M=(L+R)>>1;
if(p<=M)
Update(p,key,L,M,root<<1);
else
Update(p,key,M+1,R,root<<1|1);
PushUp(root);
}
int Query(int L,int R,int le,int ri,int root){
if(L<=le&&R>=ri)
return setTree[root];
int result=0;
int m=(le+ri)>>1;
if(L<=m)
result+=Query(L,R,le,m,root<<1);
if(R>m)
result+=Query(L,R,m+1,ri,root<<1|1);
return result;
}
int main(){
int t,n;
char oper[10];
int i,j;
cin>>t;
for(int x=1;x<=t;x++){
printf("Case %d:\n",x);
cin>>n;
Build(1,n,1);
while(scanf("%s",oper)!=EOF&&oper[0]!='E'){
cin>>i>>j;
switch(oper[0]){
case 'Q':printf("%d\n",Query(i,j,1,n,1));
break;
case 'A':Update(i,j,1,n,1);
break;
case 'S':Update(i,-j,1,n,1);
break;
}
}
}
return 0;
}
其他:宏定义用的不错
#include<cstring>
#include<iostream>
#define M 50005
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
/*left,right,root,middle*/
int sum[M<<2];
inline void PushPlus(int rt)
{
sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void Build(int l, int r, int rt)
{
if(l == r)
{
scanf("%d", &sum[rt]);
return ;
}
int m = ( l + r )>>1;
Build(lson);
Build(rson);
PushPlus(rt);
}
void Updata(int p, int add, int l, int r, int rt)
{
if( l == r )
{
sum[rt] += add;
return ;
}
int m = ( l + r ) >> 1;
if(p <= m)
Updata(p, add, lson);
else
Updata(p, add, rson);
PushPlus(rt);
}
int Query(int L,int R,int l,int r,int rt)
{
if( L <= l && r <= R )
{
return sum[rt];
}
int m = ( l + r ) >> 1;
int ans=0;
if(L<=m )
ans+=Query(L,R,lson);
if(R>m)
ans+=Query(L,R,rson);
return ans;
}
int main()
{
int T, n, a, b;
scanf("%d",&T);
for( int i = 1; i <= T; ++i )
{
printf("Case %d:\n",i);
scanf("%d",&n);
Build(1,n,1);
char op[10];
while( scanf("%s",op) &&op[0]!='E' )
{
scanf("%d %d", &a, &b);
if(op[0] == 'Q')
printf("%d\n",Query(a,b,1,n,1));
else if(op[0] == 'S')
Updata(a,-b,1,n,1);
else
Updata(a,b,1,n,1);
}
}
return 0;
}