Description
Given an N*N matrix A, whose elements are either 0 or 1. A[i, j] means the number in the i-th row and j-th column. Initially we have A[i, j] = 0 (1 <= i, j <= N).
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.
- 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).
- Q x y (1 <= x, y <= n) querys A[x, y].
Input
The first line of the input is an integer X (X <= 10) representing the number of test cases. The following X blocks each represents a test case.
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
For each querying output one line, which has an integer representing A[x, y].
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
Source
POJ Monthly,Lou Tiancheng
题意:
给出一个初始化全为0的矩阵,再给出一些操作,再讯问某些点的值.
操作1.将左下角为(x1,y1),右上角为(x2,y2)的子矩阵内所有的数进行翻转(即1变成0,0变成1)
操作2.询问点(x,y)当前的值是多少
解法:
①我们先考虑一维的情况,假设题目给定的是长度为N的一列格子d.如果我们要修改范围(x,y),那么我们就在起始点x加上1,在终点之后的位置y+1也加上1.
跟据树状数组的性质,我们可以将修改过后的树状数组数组分为三部分
1.[1,x)这段区间内的数是没有任何变化的,因此为0.
2.[x,y]这段区间内的点由于都包含了+1后的x,因此对应位置都进行了+1.
3[y+1,n]这段区间同时包含了x与y+1.所有位置都为2.
在诸多修改之后我们可以对点进行查询,查询的结果即为当前点修改过的次数,我们只需对次数mod2,就可以得到该点的值了(这也就是为什么在y+1的位置加上1就会对后面的位置没影响).
②在充分了解了一维情况后,二维情况也就是本题就变得十分轻松了.
对于要修改的一个子矩阵,我们只需修改(x1,y1),(x1,y2+1),(x2+1,y1),(x2+1,y2+1)这四个点就可以达到目的了
查询的话就按照正常树状数组查询就行了.
最后附上代码:
#include<iostream>
#include<cstring>
#define maxn 1005
using namespace std;
int c[maxn][maxn],n,m;
int lowbit(int x){
return x&(-x);
}
void update(int x,int y){
while(x<=n){
for(int i=y;i<=n;i+=lowbit(i))
c[x][i]+=1;
x+=lowbit(x);
}
}
int getsum(int x,int y){
int ans=0;
while(x>=1){
for(int i=y;i>=1;i-=lowbit(i))
ans+=c[x][i];
x-=lowbit(x);
}
return ans;
}
int main()
{
int t,x1,x2,y1,y2,k;
char op[2];
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&k);
memset(c,0,sizeof(c));
while(k--){
scanf("%s",op);
if(op[0]=='C'){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
update(x1,y1);
update(x1,y2+1);
update(x2+1,y2+1);
update(x2+1,y1);
}
else if(op[0]=='Q'){
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",getsum(x,y)%2);
}
}
if(t)
printf("\n");
}
return 0;
}