【树状数组】POJ 2155 Matrix

来源:互联网 发布:淘宝达人的推荐步骤 编辑:程序博客网 时间:2024/05/22 09:45

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


0 0
原创粉丝点击