传送门:二维树状数组模板题
分析:二维树状数组模板题,求区间和 跟 单点修改
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000+10;
const int N = 1005;
int a[maxn][maxn];
int c[maxn][maxn];
inline int lowbit(int x) {return x&(-x); }
inline void update(int x, int y, int val) {
for (int i=x; i<=N; i += lowbit(i))
for (int j=y; j<=N; j += lowbit(j)) c[i][j] += val;
}
inline int query(int x, int y) {
int sum = 0;
for (int i=x; i>0; i -= lowbit(i))
for (int j=y; j>0; j -= lowbit(j) ) sum += c[i][j];
return sum;
}
inline int Min(int x, int y) {return x<y?x:y; }
int main(){
int T;
scanf("%d",&T);
int kase = 0;
while (T--) {
printf("Case %d:\n",++kase);
memset(c,0,sizeof(c));
for (int i=1; i<=N; i++)
for (int j=1; j<=N; j++) update(i,j,1);
for (int i=1; i<=N; i++)
for (int j=1; j<=N; j++) a[i][j] = 1;
int q;
int X1,Y1,X2,Y2;
int x,y,val;
char s[10];
scanf("%d",&q);
while (q--) {
scanf("%s",s);
if (s[0] == 'S') {
scanf("%d%d%d%d",&X1,&Y1,&X2,&Y2);
if (X1>X2) swap(X1,X2);
if (Y1>Y2) swap(Y1,Y2);
X1++; Y1++; X2++; Y2++;
printf("%d\n",query(X2,Y2)-query(X2,Y1-1)-query(X1-1,Y2)+query(X1-1,Y1-1));
}
else if (s[0] == 'A') {
scanf("%d%d%d",&x,&y,&val);
x++; y++;
update(x,y,val);
a[x][y] += val;
}
else if (s[0] == 'D' ){
scanf("%d%d%d",&x,&y,&val);
x++; y++;
val = Min(a[x][y],val);
update(x,y,-val);
a[x][y] -= val;
}
else {
scanf("%d%d%d%d%d",&X1,&Y1,&X2,&Y2,&val);
X1++; Y1++; X2++; Y2++;
val = Min(a[X1][Y1],val);
update(X1,Y1,-val);
update(X2,Y2,val);
a[X1][Y1] -= val;
a[X2][Y2] += val;
}
}
}
return 0;
}