View Code
#include <stdio.h>
#include <string.h>
int n;
int a[510][510];
int lowbit(int x)
{
return x&(-x);
}
void inc(int x,int y,int z)
{
for (int j=x;j<=n;j+=lowbit(j))
for (int i=y;i<=n;i+=lowbit(i))
a[j][i]+=z;
}
long long sum(int x,int y)
{
long long s=0;
for (int i=x;i>=1;i-=lowbit(i))
for (int j=y;j>=1;j-=lowbit(j))
s+=a[i][j];
return s;
}
int main()
{
int m,k;
while (~scanf("%d%d",&n,&m))
{
memset(a,0,sizeof(a));
int i,j;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&k);
inc(i,j,k);
}
while (m--)
{
int x1,y1,x2,y2;
long long s;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
s=sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1);
printf("%lld\n",s);
}
}
return 0;
#include <string.h>
int n;
int a[510][510];
int lowbit(int x)
{
return x&(-x);
}
void inc(int x,int y,int z)
{
for (int j=x;j<=n;j+=lowbit(j))
for (int i=y;i<=n;i+=lowbit(i))
a[j][i]+=z;
}
long long sum(int x,int y)
{
long long s=0;
for (int i=x;i>=1;i-=lowbit(i))
for (int j=y;j>=1;j-=lowbit(j))
s+=a[i][j];
return s;
}
int main()
{
int m,k;
while (~scanf("%d%d",&n,&m))
{
memset(a,0,sizeof(a));
int i,j;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
scanf("%d",&k);
inc(i,j,k);
}
while (m--)
{
int x1,y1,x2,y2;
long long s;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
s=sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1);
printf("%lld\n",s);
}
}
return 0;
题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1693