一道简单的裸二维树状数组。
需要注意的是题目给出的坐标是(x>=0 and x<n),所以在处理的时候最好把坐标都加上1,就不用处理0减去1出现-1的情况了。为此还TLE了一次,囧。
下面给出代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int n,t,x,y,a,l,b,r; int m[1111][1111]; #define lowbit(x) x&(-x) void add(int i,int j,int del) { int tmpj; while (i<=n) { tmpj=j; while (tmpj<=n) { m[i][tmpj]+=del; tmpj+=lowbit(tmpj); } i+=lowbit(i); } } int query(int i,int j) { if (i*j==0) return 0; int tmpj,sum=0; while (i>0) { tmpj=j; while (tmpj>0) { sum+=m[i][tmpj]; tmpj-=lowbit(tmpj); } i-=lowbit(i); } return sum; } int main() { scanf("%d%d",&n,&n); memset(m,0,sizeof m); while (scanf("%d",&t) && t!=3) { if (t==1) { scanf("%d%d%d",&x,&y,&a); x++,y++; add(x,y,a); } else { scanf("%d%d%d%d",&l,&b,&r,&t); l++,b++,r++,t++; int ans=query(r,t)-query(r,b-1)-query(l-1,t)+query(l-1,b-1); printf("%d\n",ans); } } return 0; }