【树状数组】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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值