您的位置:首页 > 其它

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

2014-04-14 14:41 253 查看
假设原数组设为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: