http://poj.org/problem?id=1195
二维树状数组
就是比一维的多了一维而已 关键在理解
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<queue> #include<algorithm> #include<stack> using namespace std; const int N=1200; int c[N][N]; int n; int lowbit(int x) { return x&(-x); } void Add(int x,int y,int k) { for(int i=x;i<=n;i+=lowbit(i)) { for(int j=y;j<=n;j+=lowbit(j)) { c[i][j]+=k; } } } int Sum(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; } int main() { int k; while(scanf("%d",&k)!=EOF) { if(k==0) { memset(c,0,sizeof(c)); scanf("%d",&n); } if(k==1) { int x,y,k; scanf("%d %d %d",&x,&y,&k); ++x;++y; Add(x,y,k); } if(k==2) { int x1,y1,x2,y2; scanf("%d %d %d %d",&x1,&y1,&x2,&y2); ++x1;++y1;++x2;++y2; printf("%d\n",Sum(x2,y2)-Sum(x1-1,y2)-Sum(x2,y1-1)+Sum(x1-1,y1-1)); } if(k==3) { break; } } return 0; }