首页 > 代码库 > BZOJ 1452: [JSOI2009]Count (二维树状数组)

BZOJ 1452: [JSOI2009]Count (二维树状数组)

Description

Input

Output

Sample Input





Sample Output

1

2

HINT


二维树状数组的简单应用,c数组的第一维坐标相当于哈希。如果是修改操作,修改前 将当前的值的个数以及祖先都减1, 修改后将个数加1.


#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <stack>
#include <cctype>
#include <algorithm>
#define lson o<<1, l, m
#define rson o<<1|1, m+1, r
using namespace std;
typedef long long LL;
const int mod = 99999997;
const int MAX = 1000000000;
const int maxn = 100005;
int n, m, op, q;
int in[305][305], c[105][305][305];
void add(int i, int j, int x, int v) {
    while(i <= n) {
        int j1 = j;
        while(j1 <= m) {
            c[x][i][j1] += v;
            j1 += j1&-j1;
        }
        i += i&-i;
    }
}
int query(int i, int j, int v) {
    int ans = 0;
    while(i > 0) {
        int j1 = j;
        while(j1 > 0) {
            ans += c[v][i][j1];
            j1 -= j1&-j1;
        }
        i -= i&-i;
    }
    return ans ;
}
int main()
{
   // freopen("in.txt", "r", stdin);
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++) {
            cin >> in[i][j];
            add(i, j, in[i][j], 1);
        }
    cin >> q;
    while(q--) {
        scanf("%d", &op);
        if(op == 1) {
            int a, b, v;
            scanf("%d%d%d", &a, &b, &v);
            add(a, b, in[a][b], -1);
            in[a][b] = v;
            add(a, b, in[a][b], 1);
        } else {
            int x1, y1, x2, y2, v;
            scanf("%d%d%d%d%d", &x1, &x2, &y1, &y2, &v);
            int ans = query(x2, y2, v) + query(x1-1, y1-1, v) - query(x2, y1-1, v) - query(x1-1, y2, v);
            printf("%d\n", ans);
        }
    }
    return 0;
}