您的位置:首页 > 其它

【树状数组】POJ 2155 Matrix

2015-08-22 11:01 260 查看
附一篇经典翻译,学习 树状数组 http://www.hawstein.com/posts/binary-indexed-trees.html

/**
*  @author           johnsondu
*  @time             2015-8-22
*  @type             2D Binary Index Tree
*  @strategy         假设翻转的是(x1,y1), (x2,y2)区域,则相当于
*                      翻转(0, 0)~(x2, y2), 然后再翻转(0,0)~(x1-1, y2)
*                       (0, 0)~(x2, y1-1), (0, 0)~(x1-1, y1-1);
*                       因为翻转两次等于没有翻转。此处类比容斥原理
*  @url              http://poj.org/problem?id=2155 */

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <vector>

using namespace std;

const int N = 1005;
int c

, n, q;

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 query(int x, int y)
{
int sum = 0;
for(int i = x; i > 0; i -= lowbit(i))
for(int j = y; j > 0; j -= lowbit(j))
sum += c[i][j];
return sum;
}

int main()
{
int tcase;
int x1, y1, x2, y2;
scanf("%d", &tcase) ;
while(tcase --) {
memset(c, 0, sizeof(c));
scanf("%d%d", &n, &q);
for(int i = 0; i < q; i ++)
{
char command[5];
scanf("%s", command);
if(command[0] == 'C')
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
x1 ++; y1 ++; x2 ++; y2 ++;
update(x2, y2);
update(x1 - 1, y1 - 1);
update(x1 - 1, y2);
update(x2, y1 - 1);
}
else
{
scanf("%d%d", &x1, &y1);
printf("%d\n", query(x1, y1) & 1);
}
}
printf("\n");

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: