ADABEHIVE - Ada and Behives
Ada the Ladybug is currently doing her thesis. It is almost complete with one tiny exception - there are some graphs and statistics missing. The topic of thesis is "Behavior of Bee Hives". She examines population of bees and their growth in given areas.
Ada has all data she needs - but parsing it manually might take many long months. She decided to ask you for help. Basically - given population of individual bee hives you will have to answer the number of bees on give area. There are two kinds of queries:
Query of kind 1 gives you coordinates of hive and number of new-born bees.
Query of kind 2 gives you description of rectangle. You will be asked to find the number of bees living in it.
Input
The first line contains three integer numbers 1 ≤ N, M ≤ 2000, 1 ≤ Q ≤ 105, the size of examined area (number of rown and number of columns), and number of queries.
The next N lines contains M integer numbers 1 ≤ Ai,j ≤ 104, the sizes of hives.
Afterward, Q lines (of two types) follow
First kind 1 I J P, 1 ≤ I ≤ N, 1 ≤ J ≤ M, 1 ≤ P ≤ 104, the position of hive and the number of newborn bees.
Second kind 2 I1 J1 I2 J2, 1 ≤ I1 ≤ I2 ≤ N, 1 ≤ J1 ≤ J2 ≤ M, the boundaries of rectangular area for which you want to know the number of bees (more specifically the lower-left and upper right corners).
Output
For each query of second kind , output the number of bees.
Example Input
6 5 8 1 2 3 4 5 1 2 3 4 5 6 6 6 6 6 5 4 3 2 1 5 4 3 2 1 6 6 6 6 6 2 1 1 6 5 2 1 1 2 4 2 4 2 5 4 1 5 4 4 1 1 1 665 2 1 1 6 5 2 1 1 2 4 2 4 2 5 4
Example Output
120 20 18 789 685 22
二维树状数组模板题,进行单点更新,子矩阵求和。
#include<bits/stdc++.h>
#define MAXN 2005
using namespace std;
long long n,m;
long long a[MAXN][MAXN],tree[MAXN][MAXN];
long long lowbit(long long x)
{
return x&-x;
}
void add(long long x,long long y,long long p)
{
for(long long i=x;i<=n;i+=lowbit(i))
for(long long j=y;j<=m;j+=lowbit(j))
tree[i][j]+=p;
}
long long sum(long long x,long long y)
{
long long result=0;
for(long long i=x;i>0;i-=lowbit(i))
for(long long j=y;j>0;j-=lowbit(j))
result+=tree[i][j];
return result;
}
long long ask(long long x1,long long y1,long long x2,long long y2)//left-top right-low
{
return sum(x2,y2)+sum(x1-1,y1-1)-sum(x2,y1-1)-sum(x1-1,y2);
}
int main()
{
long long q;
scanf("%lld%lld%lld",&n,&m,&q);
memset(tree,0,sizeof(tree));
for(long long i=1;i<=n;i++)
{
for(long long j=1;j<=m;j++)
{
scanf("%lld",&a[i][j]);
add(i,j,a[i][j]);
}
}
for(long long i=0;i<q;i++)
{
long long op;
scanf("%lld",&op);
if(op==1)
{
long long x,y,p;
scanf("%lld%lld%lld",&x,&y,&p);
add(x,y,p);
}
else
{
long long x1,y1,x2,y2;
scanf("%lld%lld%lld%lld",&x1,&y1,&x2,&y2);
printf("%lld\n",ask(x1,y1,x2,y2));
}
}
}