題意:有一個N * N廣場,廣場裡面有一些手機,某個格子是可以改變的,增加或者減少,問一個小矩陣內有多少個手機。
思路 :裸的二維樹狀數組。
代碼:
[cpp]
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 1030;
int num[N][N];
int lowbit(int x){
return x & (-x);
}
void update(int x,int y,int add){
int t = y;
while(x < N){
y = t;
while(y < N){
num[x][y] += add;
if(num[x][y] < 0)
num[x][y] = 0;
y += lowbit(y);
}
x += lowbit(x);
}
}
LL sum(int x,int y){
int t = y;
LL s = 0;
while(x > 0){
y = t;
while(y > 0){
s += num[x][y];
y -= lowbit(y);
}
x -= lowbit(x);
}
return s;
}
int main(){
//freopen("1.txt","r",stdin);
int id,n;
while(scanf("%d%d",&id,&n) != EOF){
memset(num,0,sizeof(num));
int x1,y1,x2,y2,value;
while(1){
scanf("%d",&id);
if(id == 3)
break;
else if(id == 1){
scanf("%d%d%d",&x1,&y1,&value);
update(x1+1,y1+1,value);
}
else if(id == 2){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
printf("%lld\n",sum(x2+1,y2+1) - sum(x1,y2+1) - sum(x2+1,y1) + sum(x1,y1));
}
}
}
return 0;
}