首先看数据,显然地,暴力 做法会 TLE,所以考虑使用二维前缀和。 关于二维前缀和的资料看 这里, 这里运用 公式 (来自 _HJL),直接计算。
#include<iostream>
#define ll long long
#define rll register ll
#define F(i,a,b) for(rll i=a;i<=b;i++)
using namespace std;
const int maxn = 1000 + 7;
struct node{
int j, o, i;
}s[maxn][maxn];//结构体存储前缀和数组
int n, m, k;
int main(){
cin >> n >> m >> k;
F(i, 1, n){
F(j, 1, m){
char cxk;
cin >> cxk;
if(cxk == 'J'){
s[i][j].j++;
}else if(cxk == 'O'){
s[i][j].o++;
}else if(cxk == 'I'){
s[i][j].i++;
}
s[i][j].j += s[i - 1][j].j + s[i][j - 1].j - s[i - 1][j - 1].j;
s[i][j].o += s[i - 1][j].o + s[i][j - 1].o - s[i - 1][j - 1].o;
s[i][j].i += s[i - 1][j].i + s[i][j - 1].i - s[i - 1][j - 1].i;
}//二维前缀和处理
}
int x1, y1, x2, y2;
F(i, 1, k){
cin >> x1 >> y1 >> x2 >> y2;
cout<< s[x2][y2].j - s[x1 - 1][y2].j - s[x2][y1 - 1].j + s[x1 - 1][y1 - 1].j <<" "
<<s[x2][y2].o - s[x1 - 1][y2].o - s[x2][y1 - 1].o + s[x1 - 1][y1 - 1].o<< " "
<<s[x2][y2].i - s[x1 - 1][y2].i - s[x2][y1 - 1].i + s[x1 - 1][y1 - 1].i << endl;
}//查询输出
return 0;
}