poj 2155 树状数组

照着以下资料初步学习了树状数组:

树状数组题目集.pdf  http://download.youkuaiyun.com/detail/handong1587/5659973

http://dongxicheng.org/structure/binary_indexed_tree/

http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees 讲的很详细!

里面用到位运算,感觉有点奇淫巧计的意思。理解了原始数组与树状数组的对应关系之后就比较简单了,不过想做进一步的应用就得多多练习了。

下面代码AC过了,不过很奇怪,编译器选G++老是提示超时,选C++就能AC,Memory:4204K,Time:1672MS。


#include <iostream>
#include <cstring>

using namespace std;

int X, N, T;
int matrix[1005][1005];

void updateMatVal(int x, int y, int val)
{
	while (x <= N) {
		int tmpy = y;
		while (tmpy <= N) {
			matrix[x][tmpy] += val;	
			tmpy += tmpy & (-tmpy);
		}
		x += x & (-x);
	}
}
void update2D(int x1, int y1, int x2, int y2)
{
	updateMatVal(x1, y1, 1);
	updateMatVal(x1, y2+1, -1);
	updateMatVal(x2+1, y1, -1);
	updateMatVal(x2+1, y2+1, 1);
}

int getMatSum(int x, int y)
{
	int sum = 0;
	while (x > 0) {
		int tmpy = y;
		while (tmpy > 0) {
			sum += matrix[x][tmpy];
			tmpy -= tmpy & (-tmpy);
		}
		x -= x & (-x);
	}
	return sum;
}

int main()
{
	//freopen("POJ2155_Matrix.txt", "r", stdin);
	cin>>X;
	while (X--) {
		cin>>N>>T;
		memset(matrix, 0, sizeof(matrix));
		for (int j=0; j<T; j++) {
			char cmd;
			cin>>cmd;
			if (cmd == 'Q') {
				int x, y;
				cin>>x>>y;
				cout<<getMatSum(x, y)%2<<endl;
			}
			if (cmd == 'C') {
				int x1, y1, x2, y2;
				cin>>x1>>y1>>x2>>y2;
				update2D(x1, y1, x2, y2);
			}
		}
		if (X > 0)
			cout<<endl;
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值