POJ 1195 - Moblie phones


—— by A Code Rabbit


Description

在一个矩阵上面进行一些操作。

将矩阵某一个位置上的数字增加,

或者是询问某个子矩阵内的数值之和。

对于每个询问,输出结果。


Type

Advanced Data Structures :: Segment Tree

Advanced Data Structures :: Binary Indexed Tree


Analysis

经典的二维树状数组。

只是将一维 BIT 变成二维 BIT 的过程而已。

然后求和的时候,利用类似集合操作的方法求和。

还是要注意 BIT 下标不能为 0 的问题。


Solution

// POJ 1195
// Mobile phones
// by A Code Rabbit

#include <cstdio>
#include <cstring>

const int MAXN = 1026;
const int MAXM = 1026;

struct Bit2D {
    int c[MAXN][MAXM], n, m;
    void Init(int x, int y) { memset(c, 0, sizeof(c)); n = x; m = y; }
    void Add(int x, int y, int z) {
        int tmp = y;
        while (x <= n) {
            y = tmp;
            while (y <= m) {
                c[x][y] += z;
                y += y & -y;
            }
            x += x & -x;
        }
    }
    int Sum(int x, int y) {
        int res = 0;
        int tmp = y;
        while (x > 0) {
            y = tmp;
            while (y > 0) {
                res += c[x][y];
                y -= y & -y;
            }
            x -= x & -x;
        }
        return res;
    }
};

int instruction, s;
int x, y, a;
int l, b, r, t;
Bit2D bit;

int main() {
    while (scanf("%d", &instruction)) {
        if (instruction == 0) {
            scanf("%d", &s);
            bit.Init(s, s);
        } else
        if (instruction == 1) {
            scanf("%d%d%d", &x, &y, &a);
            bit.Add(x + 1, y + 1, a);
        } else
        if (instruction == 2) {
            scanf("%d%d%d%d", &l, &b, &r, &t);
            int ans = bit.Sum(r + 1, t + 1)
                - bit.Sum(l, t + 1)
                - bit.Sum(r + 1, b)
                + bit.Sum(l, b);
            printf("%d\n", ans);
        } else
        if (instruction == 3) {
            break;
        }
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值