二维树状数组也是固定写好的,用的时候只要改改main函数就好。
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define maxn 10000
int tree[maxn][maxn],mark[maxn][maxn];
int lowbit(int i){
return i&(-i);
}
void update(int x,int y,int t){
for(int i=x;i<maxn;i+=lowbit(i)){
for(int j=y;j<maxn;j+=lowbit(j)){
tree[i][j]+=t;
}
}
}
int query(int x,int y){
int sum,i,j;
for(i=x;i>0;i-=lowbit(i))
for(j=y;j>0;j-=lowbit(j))
sum+=tree[i][j];
return sum;
}
int main(){
int n,x,y,x1,x2,y1,y2;
char s[3];
scanf("%d",&n);
while(n--){
scanf("%s",s);
if(s[0]=='B'){
scanf("%d%d",&x,&y);
x++;
y++;
if(mark[x][y]==0){
mark[x][y]=1;
update(x,y,1);
}
}
else if(s[0]=='D'){
scanf("%d%d",&x,&y);
x++;
y++;
if(mark[x][y]==1){
mark[x][y]=0;
update(x,y,-1);
}
}
else if(s[0]=='Q'){ /*query是往回查*/
scanf("%d%d%d%d",&x1,&x2,&y1,&y2);
x1++;
x2++;
y1++;
y2++;
if(x1>x2)
swap(x1,x2);
if(y1>y2)
swap(y1,y2);
int res=query(x2,y2)-query(x1-1,y2)-query(x2,y1-1)+query(x1-1,y1-1);
printf("%d\n",res);
}
}
return 0;
}