【树状数组】POJ 2155 Matrix

附一篇经典翻译,学习 树状数组  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][N], 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; }



posted @ 2017-05-27 08:39  yfceshi  阅读(145)  评论(0编辑  收藏  举报