Description
Input
For each test case, the first line contains two integers m, n (1 <= m, n <= 300), which is the size of the row and column of the matrix, respectively. The next m lines with n integers each gives the elements of the matrix which fit in non-negative 32-bit integer.
The next line contains a single integer Q (1 <= Q <= 1,000,000), the number of queries. The next Q lines give one query on each line, with four integers r1, c1, r2, c2 (1 <= r1 <= r2 <= m, 1 <= c1 <= c2 <= n), which are the indices of the upper-left corner and lower-right corner of the sub-matrix in question.
Output
Sample Input
4 4 10 7
2 13 9 11
5 7 8 20
13 20 8 2
4
1 1 4 4
1 1 3 3
1 3 3 4
1 1 1 1
Sample Output
13 no
20 yes
4 yes
Source
二维RMQ练习题。
一维RMQ二分维护一个区间,而二维RMQ通过维护四个等分的矩形区间维护了一个区间的最值,基本原理差不多
理解的还不是很透彻,代码基本靠抄。
这题内存限制范围很小,数组稍微开大就MLE
/*by SilverN*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int f[][][][];
//f[i][j][x][y]记录以(i,j)为左上角,(i+(1<<x),j+(1<<y))为右下角的矩形内的最大值
int mp[][];
int n,m;
void init(){
int i,j;
int k,l;
for(i=;i<=n;i++)
for(j=;j<=m;j++)
f[i][j][][]=mp[i][j];
int kn=(int)(log((double)n)/log(2.0));
int km=(int)(log((double)m)/log(2.0));
for(i=;i<=kn;i++)
for(j=;j<=km;j++){
if(i== && j==)continue;
for(k=;k+(<<i)-<=n;k++)
for(l=;l+(<<j)-<=m;l++){
if(!i)//i==0 && j!=0
f[k][l][i][j]=max(f[k][l][i][j-],f[k][l+(<<(j-))][i][j-]);
else //i!=0
f[k][l][i][j]=max(f[k][l][i-][j],f[k+(<<(i-))][l][i-][j]);
}
}
return;
}
int RMQ(int x1,int y1,int x2,int y2){
int kn=(int)(log(double(x2-x1+))/log(2.0));
int km=(int)(log(double(y2-y1+))/log(2.0));
int a=max(f[x1][y1][kn][km],f[x2-(<<kn)+][y1][kn][km]);
int b=max(f[x1][y2-(<<km)+][kn][km],f[x2-(<<kn)+][y2-(<<km)+][kn][km]);
return max(a,b);
}
int main(){
int i,j;
int k;
while(scanf("%d%d",&n,&m)!=-){ for(i=;i<=n;i++)
for(j=;j<=m;j++)
scanf("%d",&mp[i][j]);
init();
int x1,x2,y1,y2;
scanf("%d",&k);
while(k--){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
int ans=RMQ(x1,y1,x2,y2);
printf("%d ",ans);
if(ans==mp[x1][y1] || ans==mp[x2][y2] || ans==mp[x1][y2] || ans==mp[x2][y1])
puts("yes");
else puts("no");
}
}
return ;
}