题意:是输入一个矩阵,然后再输入Q条指令,每条指令是一个子矩阵的两个对角顶点,让求这个子矩阵元素的最大值。然后看这个最大值和子矩阵的4个顶点有没有相同的,如果有,再输出“yes”,没有输出“no”。
解题方法:裸2维RMQ,注意内存限制紧,要尽量往小开。
#include <bits/stdc++.h>
using namespace std;
//2DRMQ
const int N = 301;
int n, m, a[N][N], dp[301][301][9][9];
void D2_RMQ(){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
dp[i][j][0][0] = a[i][j];
}
}
for(int i = 0; (1 << i) <= n; i++){
for(int j = 0; (1 << j) <= m; j++){
if(i == 0 && j == 0) continue;
for(int r = 1; r + (1 << i) - 1 <= n; r++){
for(int c = 1; c + (1 << j) -1 <= m; c++){
//当i或j等于0的时候,就相当于一维的RMQ了
if(i == 0) dp[r][c][i][j] = max(dp[r][c][i][j - 1], dp[r][c + (1 << (j - 1))][i][j - 1]);
else if (j == 0) dp[r][c][i][j] = max(dp[r][c][i - 1][j], dp[r + (1 << (i - 1))][c][i - 1][j]);
else dp[r][c][i][j] = max(dp[r][c][i][j - 1], dp[r][c + (1 << (j - 1))][i][j - 1]);
}
}
}
}
}
//本来一维RMQ询问的时候是一个区间,现在变成了一个矩形,所以需要四个角度
int Query(int x1, int y1, int x2, int y2) {
int kx = 0, ky = 0;
while (x1 + (1 << (1 + kx)) - 1 <= x2) kx++;
while (y1 + (1 << (1 + ky)) - 1 <= y2) ky++;
int m1 = dp[x1][y1][kx][ky];
int m2 = dp[x2 - (1 << kx) + 1][y1][kx][ky];
int m3 = dp[x1][y2 - (1 << ky) + 1][kx][ky];
int m4 = dp[x2 - (1 << kx) + 1][y2 - (1 << ky) + 1][kx][ky];
return max(max(m1, m2), max(m3, m4));
}
int main(){
while(scanf("%d%d", &n, &m) != EOF){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
scanf("%d", &a[i][j]);
}
}
D2_RMQ();
int q;
scanf("%d", &q);
while(q--){
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
int mx = Query(x1, y1, x2, y2);
if(mx == a[x1][y1] || mx == a[x2][y2] || mx == a[x1][y2] || mx == a[x2][y1]){
printf("%d yes\n", mx);
}
else{
printf("%d no\n", mx);
}
}
}
return 0;
}