—— 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;
}