继续二维树状数组 pku1195

 
 
设想一个矩形,左上角坐标为(x1,y1),右下角坐标为(x2,y2),现在我们对其利用二维树状数组进行区间求和
sum(x2,y2)表示0,0--》x2,y2大矩形求和,sum(x1-1,y2)表示0,0->x1-1,y2求和
sum(x2,y1-1)、sum(x1-1,y1-1)同理,
sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1)即为所求矩形内的和
跟一维其实一样,形变而神不变
View Code
#include<stdio.h>
#include
<string.h>
int n;
int c[1025][1025];
int lowbit(int x)
{
return x&(-x);
}
void add(int x,int y,int num)
{
int i,j;
for(i=x;i<=n;i+=lowbit(i))
for(j=y;j<=n;j+=lowbit(j))
c[i][j]
+=num;
}
int sum(int x,int y)
{
int i,j,s=0;
for(i=x;i>=1;i-=lowbit(i))
for(j=y;j>=1;j-=lowbit(j))
s
+=c[i][j];
return s;
}
int main()
{
int x1,y1,x2,y2,mark,a,b,x;
while(scanf("%d",&mark)!=EOF)
{
if(mark==0)
{
scanf(
"%d",&n);
n
++;
memset(c,
0,sizeof(c));
}
else if(mark==1)
{
scanf(
"%d%d%d",&a,&b,&x);
a
++,b++;
add(a,b,x);
}
else if(mark==2)
{
scanf(
"%d%d%d%d",&x1,&y1,&x2,&y2);
x1
++;x2++;y1++;y2++;
printf(
"%d\n",sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1));
}
else break;
}
return 0;
}

  

你可能感兴趣的:(继续二维树状数组 pku1195)