[poj 2155] Matrix(二维树状数组)


假设原数组设为num, 树状数组设为c。
一维的树状数组操作:
    区间[x, y]取反,那么就在原数组上num[x]++,num[y+1]++,即update(x, 1), update(y+1, 1)。
    求num[x]的状态,就re = getsum(x),判断re%2的值即可。
推广到二维也是一样的:
    矩阵[x1, y1] - [x2, y2]取反:就在num[x1, y1]、num[x2+1, y2+1]、num[x1, y2+1]、num[x2+1, y1]上各自+1。
    求[x, y]的状态:re = getsum(x, y),判断re%2的值。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

#define maxn 1010
int c[maxn][maxn];
int n, m;

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

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

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

void init(int n)
{
for(int i = 0; i <= n+1; i++)
{
for(int j = 0; j <= n+1; j++)
{
c[i][j] = 0;
}
}
}

int main()
{
int tot;
scanf("%d", &tot);
char op[5];
int a, b, c, d;
while(tot--)
{
scanf("%d%d", &n, &m);
init(n);
while(m--)
{
scanf("%s%d%d", op, &a, &b);
if(op[0] == 'C')
{
scanf("%d%d", &c, &d);
update(a, b);
update(c+1, d+1);
update(a, d+1);
update(c+1, b);
}
else if(op[0] == 'Q')
{
int re = getsum(a, b);
printf("%d\n", re&1);
}
}
putchar(10);
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值