POJ 1656 二维树状数组

题意:给定100*100的网格,每个格子可以涂上黑色或者白色(初始时全部树白色),经过一系列操作后输出任意一个正方形区域内的黑色格子数。

#include <iostream>
using namespace std;

int c[110][110];
int a[110][110];
const int n = 100;

int lowbit ( int x )
{
	return x & ( -x );
}

void modify ( int x, int y, int v )
{
	for ( int i = x; i <= n; i += lowbit(i) )
	{
		for ( int j = y; j <= n; j += lowbit(j) )
			c[i][j] += v;
	}
}

void update ( int x, int y, int l, int mark )
{
	int x1 = x, x2 = x + l - 1, y1 = y, y2 = y + l - 1;
	for ( int i = x1; i <= x2; ++i )
	{
		for ( int j = y1; j <= y2; ++j )
		{
			if ( a[i][j] != mark )
			{
				a[i][j] = mark;
				modify ( i, j, mark );
			}
		}
	}
}

int sum ( int x, int y )
{
	int total = 0;
	for ( int i = x; i > 0; i -= lowbit(i) )
	{
		for ( int j = y; j > 0; j -= lowbit(j) )
			total += c[i][j];
	}
	return total;
}

int getSum ( int x, int y, int l )
{
	int x1 = x, y1 = y, x2 = x + l - 1, y2 = y + l - 1;
	return sum ( x2, y2 ) - sum ( x1-1, y2 ) - sum( x2 , y1 - 1 ) + sum ( x1 - 1, y1 - 1);
}

int main()
{
	int t, x, y, l;
	char oper[10];
	memset(c,0,sizeof(c));
	memset(a,-1,sizeof(a));
	scanf("%d", &t );
	while ( t-- )
	{
		scanf("%s", oper );
		scanf("%d%d%d", &x, &y, &l );
		if ( strcmp(oper, "BLACK") == 0 )
			update ( x, y, l, 1 );
		else if ( strcmp(oper, "WHITE") == 0 )
			update ( x, y, l, -1 );
		else
			printf ( "%d\n", getSum ( x, y, l ) );
	}
	return 0;
}


此题直接求解0MS
#include <iostream>
using namespace std;

int a[110][110];

void update ( int x1, int y1, int x2, int y2, bool mark )
{
	for ( int i = x1; i <= x2; ++i )
		for ( int j = y1; j <= y2; ++j )
			a[i][j] = mark;
}

int getSum ( int x1, int y1, int x2, int y2 )
{
	int i, j, sum = 0;
	for ( i = x1; i <= x2; ++i )
		for ( j = y1; j <= y2; ++j )
			if ( a[i][j] )
				++sum;
	return sum;
}

int main()
{
	int t, x, y, l;
	char oper[10];
	memset(a,0,sizeof(a));
	scanf("%d", &t );
	while ( t-- )
	{
		scanf("%s", oper );
		scanf("%d%d%d", &x, &y, &l );
		if ( strcmp(oper, "BLACK") == 0 )
			update ( x, y, x+l-1, y+l-1, 1 );
		else if ( strcmp(oper, "WHITE") == 0 )
			update ( x, y, x+l-1, y+l-1, 0 );
		else
			printf ( "%d\n", getSum ( x, y, x+l-1, y+l-1 ) );
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值