Matrix_二维树状数组
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
【题意】给出一个n*n的方阵,刚开始都为0;然后q个要求,c x1 y1 x2,y2表示左上角(x1,y1)右下角(x2,y2)的这个矩形里面的各方格与现在状态相反(即0变1,1变0),Q x1 y1问(x1,y1)的状态。
【思路】二维树状数组,每次状态变化都加一,最后对2取余
参考资料:http://www.cnblogs.com/lvpengms/archive/2010/04/24/1719133.html
当对(x1,y1),(x2,y2)区间置反时,需要改动四个地方就是4个角就可以了。为什么呢?如下图,假设A区未需要置反的区域,因为改动A区的左上角时,由树状数组的性质知:A,B,C,D4个区域都是要被置反的,所以在依次置反BD,CD,D,这样,置反的总过程为ABCD,BD,CD,D,这样我们就会发现结果对2取模时,只有A区被置反,B,C,D三个区都没有变化。明白原理之后就好做了。
A |
B |
C |
D |
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int N=;
int c[N][N];
int q,n;
int lowbit(int x)
{
return x&(-x);
}
int get_sum(int x,int y)
{
int ans=;
for(int i=x;i>;i-=lowbit(i))
for(int j=y;j>;j-=lowbit(j))
ans+=c[i][j];
return ans;
}
void update(int x,int y,int data)
{
for(int i=x;i<=n;i+=lowbit(i))
for(int j=y;j<=n;j+=lowbit(j))
c[i][j]+=data;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&q);
memset(c,,sizeof(c));
char op[];
int x1,y1,x2,y2;
while(q--)
{
scanf("%s",op);
if(op[]=='C')
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
update(x1,y1,);
update(x2+,y1,);
update(x1,y2+,);
update(x2+,y2+,);
}
else
{
scanf("%d%d",&x1,&y1);
if(get_sum(x1,y1)%==) puts("");
else puts("");
}
}
if(t>) puts("");
}
return ;
}
最新文章
- Linux文件查找命令find,xargs详述
- h5 -1
- Java 8 新特性概述
- PropertyPlaceholderConfigurer类的使用注意
- return 使用和闭包
- linux C 文件操作之fscanf()
- 串String(2):串的实现(堆分配存储表示法)
- java 日常学习记录-反射
- 使用ACR122U NFC读卡器对M1卡进行读写操作(可以读写中文)
- c# partial 关键字的使用
- tensorflow学习笔记————分类MNIST数据集
- 用redux-thunk异步获取数据
- 《Attention is All You Need》浅读(简介+代码)
- 使用VUE搭建tab标签组件
- ssiOS应用架构谈 本地持久化方案及动态部署
- hdu-6319-单调队列
- 用absolute进行页面的自适应布局
- KnockoutJs学习笔记(四)
- 【转】Mysql两种存储引擎的异同【MyISAM和InnoDB】
- Winform开发常用控件之TreeView菜单导航和权限用法