树状数组
一维树状数组
int lowbit(int n) return n & (-n);
void update (int x, int y) {
for (; x <= N; x += lowbit(x)) c[x] += y;
}
int sum (int x) {
int ans = 0;
for (; x; x -= lowbit(x)) ans += c[x];
return ans;
}
二维树状数组
void update (int x, int y, int z) {
for (int i = x; i <= N; i += lowbit(i)) {
for (int j = y; j <= N; j += lowbit(j)) {
c[i][j] += z;
}
}
}
int sum (int x, int y) {
int ans = 0;
for (int i = x; i; i -=lowbit(i)) {
for (int j = y; j; j -= lowbit(j)) {
ans += c[i][j];
}
}
return ans;
}
树状数组:单点修改,区间查询
单点修改x, y => update(x, y)
区间查询 => sum(x)实现的是求[1, x]的和,求[L, R]的和就是sum(R) - sum(L - 1)
树状数组:区间修改,单点查询
树状数组:区间修改,区间查询
修改区间[l, r] => update(l, 1, startTree), update(r, 1, endTree);
区间查询[L, R] => sum(R, startTree) - sum(L - 1, endTree);
二维树状数组: 单点修改,区间查询
单点修改(x, y), z => update(x, y, z)
区间查询[X1, Y1], [X2, Y2] => sum(X2, Y2) - sum(X1 - 1, Y2) - sum(X2, Y1 - 1)+ sum(X1 - 1, Y1 - 1)