题目链接:见这里
解题方法: 二维树状数组,对每个颜色建一个二维树状数组。
代码如下:
#include <bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
int maze[305][305];
int c[110][305][305];
int n, m, q;
void update(int x, int y, int cc, int val){
for(int i = x; i <= n; i += lowbit(i)){
for(int j = y; j <= m; j += lowbit(j)){
c[cc][i][j] += val;
}
}
}
int query(int x, int y, int cc){
int res = 0;
for(int i = x; i; i -= lowbit(i)){
for(int j = y; j; j -= lowbit(j)){
res += c[cc][i][j];
}
}
return res;
}
int main(){
while(scanf("%d%d", &n, &m) != EOF)
{
memset(c, 0, sizeof(c));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
scanf("%d", &maze[i][j]);
update(i, j, maze[i][j], 1);
}
}
scanf("%d", &q);
while(q--){
int op;
scanf("%d", &op);
if(op == 1){
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
update(x, y, maze[x][y], -1);
maze[x][y] = c;
update(x, y, maze[x][y], 1);
}
else{
int x1, y1, x2, y2, c;
scanf("%d%d%d%d%d", &x1, &x2, &y1, &y2, &c);
int ans = query(x2, y2, c) + query(x1 - 1, y1 - 1, c) - query(x2, y1 - 1, c) - query(x1 - 1, y2, c);
printf("%d\n", ans);
}
}
}
return 0;
}