Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 14826 | Accepted: 5583 |
Description
We can change the matrix in the following way. Given a rectangle whose upper-left corner is (x1, y1) and lower-right corner is (x2, y2), we change all the elements in the rectangle by using "not" operation (if it is a '0' then change it into '1' otherwise change it into '0'). To maintain the information of the matrix, you are asked to write a program to receive and execute two kinds of instructions.
1. C x1 y1 x2 y2 (1 <= x1 <= x2 <= n, 1 <= y1 <= y2 <= n) changes the matrix by using the rectangle whose upper-left corner is (x1, y1) and lower-right corner is (x2, y2).
2. Q x y (1 <= x, y <= n) querys A[x, y].
Input
The first line of each block contains two numbers N and T (2 <= N <= 1000, 1 <= T <= 50000) representing the size of the matrix and the number of the instructions. The following T lines each represents an instruction having the format "Q x y" or "C x1 y1 x2 y2", which has been described above.
Output
There is a blank line between every two continuous test cases.
Sample Input
1
2 10
C 2 1 2 2
Q 2 2
C 2 1 2 1
Q 1 1
C 1 1 2 1
C 1 2 1 2
C 1 1 2 2
Q 1 1
C 1 1 2 1
Q 2 1
Sample Output
1
0
0
1
树状数组好强大,在这一题中,说是原始都是一些0 1,通过操作可以使1变0 0变1,在这一题中,我们可以发现,是一个区间的更新,然后是,求得一个点的值,这和我们一般用法刚好相反,其实,我们可以转换角度,其实,如果,是从最上向下更新,然后从下到上求和,这样,我们不就把一个点的值,转化成了求一个区间的值了么?也就基于这样的思想,我们在实际的用法中,要注意把向下的时候,+1然后,在重叠处-1,画画图就知道了!说也说不清楚!很好的题啊!原本是想弄线段树的,但是有的复杂,还有可以暴内存!
#include<iostream>
#include <string.h>
#include<stdio.h>
using namespace std;
#define MAXN 1005
int n;
int matrix[MAXN][MAXN];
int lowbit(int x)
{
return x&(-x);
}
int change(int x,int y,int val)//从上到下更新
{
int i,j;
for(i=x;i<=n;i=i+lowbit(i))
for(j=y;j<=n;j=j+lowbit(j))
{
matrix[i][j]+=val;
}
return 0;
}
int getsum(int x,int y)//从下向上求和
{
int i,j,re=0;
for(i=x;i>0;i=i-lowbit(i))
for(j=y;j>0;j=j-lowbit(j))
{
re+=matrix[i][j];
}
return re;
}
int main ()
{
int tcase,ask,x1,x2,y1,y2;
char c;
scanf("%d",&tcase);
while(tcase--)
{
memset(matrix,0,sizeof(matrix));
scanf("%d%d",&n,&ask);
getchar();
while(ask--)
{
c=getchar();
if(c=='C')
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
x2++;y2++;
change(x1,y1,1);
change(x2,y2,1);
change(x1,y2,-1);
change(x2,y1,-1);
}
else
{
scanf("%d%d",&x1,&y1);
printf("%d\n",1&getsum(x1,y1));//判定奇偶
}
getchar();
}
printf("\n"); }
return 0;
}