Description
一个书架有很多格,每个格子里面有一本书,现在有四种操作:
1.S x1 y2 x2 y2:查询(x1,y1)格子到(x2,y2)格子之间书的总数
2.A x1 y2 n1:往(x1,y1)格子中放进n1本书
3.D x1 y1 n1:从(x1,y1)格子中拿出n1本书(如果不够就全拿走)
4.M x1 y1 x2 y2 n1:从(x1,y1)格子往(x2,y2)格子移动n1本书(如果不够就全拿走)
Input
第一行为一个整数T表示用例组数,每组用例第一行为一整数q表示操作数,之后q行每行表示一种操作
(1<=T<=10,1< q<=100000,0<=x1,y1,x2,y2<=1000,1<=n1<=100)
Output
对于每次查询,输出查询结果
Sample Input
2
3
S 1 1 1 1
A 1 1 2
S 1 1 1 1
3
S 1 1 1 1
A 1 1 2
S 1 1 1 2
Sample Output
Case 1:
1
3
Case 2:
1
4
Solution
二维树状数组
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 1111
#define lowbit(x) ((x)&(-x))
int t,n,b[maxn][maxn];
void update(int x,int y,int v)
{
for(int i=x;i<maxn;i+=lowbit(i))
for(int j=y;j<maxn;j+=lowbit(j))
b[i][j]+=v;
}
int sum(int x,int y)
{
int ans=0;
for(int i=x;i>0;i-=lowbit(i))
for(int j=y;j>0;j-=lowbit(j))
ans+=b[i][j];
return ans;
}
int main()
{
int res=1;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",res++);
scanf("%d",&n);
memset(b,0,sizeof(b));
for(int i=1;i<maxn;i++)
for(int j=1;j<maxn;j++)
update(i,j,1);
while(n--)
{
int x1,y1,x2,y2,z;char op[11];
scanf("%s",op);
if(op[0]=='S')
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(x1>x2)swap(x1,x2);
if(y1>y2)swap(y1,y2);
int ans=sum(x2+1,y2+1)+sum(x1,y1)-sum(x1,y2+1)-sum(x2+1,y1);
printf("%d\n",ans);
}
else if(op[0]=='A')
{
scanf("%d%d%d",&x1,&y1,&z);
update(x1+1,y1+1,z);
}
else if(op[0]=='D')
{
scanf("%d%d%d",&x1,&y1,&z);
int tz=sum(x1+1,y1+1)+sum(x1,y1)-sum(x1,y1+1)-sum(x1+1,y1);
z=min(z,tz);
update(x1+1,y1+1,-z);
}
else if(op[0]=='M')
{
scanf("%d%d%d%d%d",&x1,&y1,&x2,&y2,&z);
int tz=sum(x1+1,y1+1)+sum(x1,y1)-sum(x1,y1+1)-sum(x1+1,y1);
z=min(z,tz);
update(x1+1,y1+1,-z);
update(x2+1,y2+1,z);
}
}
}
}