题目链接:http://poj.org/problem?id=1195
题意:给一个二维矩阵,每次在一个点上增加一个值,或者求一个矩形范围内的和。
思路:二维树状数组模板,查询的时候,如果我们query(x2,y2)是求的从(1,1,)到(x2,y2)的所有和。
所以答案是q(x2,y2)-q(x2,y1-1)-q(x1-1,y2)+q(x1-1,y1-1)
树状数组专题链接:http://blog.csdn.net/chy20142109/article/details/50673749
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
#define LL long long
#define rep(i,j,k) for(int i = j; i <= k; i++ )
#define Rrep(i,j,k) for(int i = j; i >= k; i-- )
#define Clean(x,y) memset(x,y,sizeof(x))
int n;
int op;
int a,b,c,d;
LL sum[1100][1100];
int lowbit(int x)
{
return x&(-x);
}
void add(int x,int y,int z)
{
while( x<=n )
{
int ty = y;
while( ty<=n )
{
sum[x][ty]+=z;
ty+=lowbit(ty);
}
x+=lowbit(x);
}
}
LL query(int x,int y)
{
LL ans = 0;
while(x>0)
{
int ty = y;
while( ty>0 )
{
ans+=sum[x][ty];
ty-=lowbit(ty);
}
x-=lowbit(x);
}
return ans;
}
int main()
{
while(cin>>op)
{
cin>>n;
Clean(sum,0);
while(~scanf("%d",&op))
{
if ( op == 3 ) break;
else if( op == 1 )
{
scanf("%d %d %d",&a,&b,&c);
a++;b++;
add(a,b,c);
}
else
{
scanf("%d %d %d %d",&a,&b,&c,&d);
a++;b++;d++;c++;
printf("%I64d\n",query(c,d)-query(c,b-1)-query(a-1,d)+query(a-1,b-1));
}
}
}
return 0;
}