Matrix

链接:http://poj.org/problem?id=2155

题目: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.

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].

题意:有一个矩阵,里面所有数字都是0,有两种操作,c操作,把一个矩形里的数字都取非,q操作,展示某个点的值。

分析:这道题是今天补得,这种状态有限且循环的题是可以记录改变次数,通过次数求解的,所以用二位的树状数组记录改变次数即可。然而,每个点都记录是不行的,一个巧妙的办法是,改变的时候,只更改矩形起点处的改变次数,以及另外三个边界点之后的点的改变次数。这样区域内的点在计算更改次数时通过树状数组的特性就是更改过一次的,而超过区域的在计算的时候与原来相比更改了0或者2次,即为没更改过。这个技巧非常巧妙。

题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define pii pair<int,int>
#define lowbit(x) x&(-x)
using namespace std;
#define maxi 0x3f3f3f3f
#define MAX 1005

int bit[MAX][MAX];
int X;
int N, T;

void add(int x, int y, int a)
{
	for (int i = x; i <= N; i += lowbit(i))
	{
		for (int j = y; j <= N; j += lowbit(j))
		{
			bit[i][j] += a;
		}
	}
}

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 += bit[i][j];
		}
	}
	rt ans;
}

int main()
{
	//fr;
	detie;
	scanf("%d", &X);
	while (X--)
	{

		char c[10];
		int x1, x2, y1, y2;
		memset(bit, 0, sizeof bit);
		scanf("%d %d", &N, &T);
		while (T--)
		{
			scanf("%s", c);
			if (c[0]=='C')
			{
				scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
				add(x1, y1, 1);
				add(x1, y2 + 1, 1);
				add(x2 + 1, y1, 1);
				add(x2 + 1, y2 + 1, 1);
			}
			else
			{
				scanf("%d %d", &x1, &y1);
				printf("%d\n", sum(x1, y1)&1);
			}
		}
		printf("\n");
	}
	rt 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值