Largest Submatrix
You are given an matrix M (consisting of nonnegative integers) and an integer K. For any submatrix of M' of M define min(M') to be the minimum value of all the entries of M'. Now your task is simple: find the maximum value of min(M') where M' is a submatrix of M of area at least K (where the area of a submatrix is equal to the number of rows times the number of columns it has).
Input
The first line contains a single integer T (T ≤ 10) denoting the number of test cases, T test cases follow. Each test case starts with a line containing three integers, R (R ≤ 1000), C (C ≤ 1000) and K (K ≤ R * C) which represent the number of rows, columns of the matrix and the parameter K. Then follow R lines each containing C nonnegative integers, representing the elements of the matrix M. Each element of M is ≤ 10^9
Output
For each test case output two integers: the maximum value of min(M'), where M' is a submatrix of M of area at least K, and the maximum area of a submatrix which attains the maximum value of min(M'). Output a single space between the two integers.
Example
Input: 2 2 2 2 1 1 1 1 3 3 2 1 2 3 4 5 6 7 8 9 Output: 1 4 8 2
题解:二分答案 对于每次二分 创造出一个新的01矩阵 1代表当前为比此答案大 0代表小 问题就转化成了最大01子矩阵
用单调栈求解子矩阵
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k;
int a[1005][1005],b[1005][1005],d[1005],lef[1005][1005],rig[1005][1005];
int solve(int x) {
int i,j,ans;ans=0;
for(j=1;j<=m;j++)b[1][j]=(a[1][j]>=x);
for(i=2;i<=n;i++)for(j=1;j<=m;j++)b[i][j]=(a[i][j]>=x)?(1+b[i-1][j]):0;
for(i=1;i<=n;i++)
{
d[0]=1;
d[1]=lef[i][1]=1;
for(j=2;j<=m;j++)
{
while(d[0]>0&&b[i][d[d[0]]]>=b[i][j])d[0]--;
lef[i][j]=(d[0])?(d[d[0]]+1):1;d[++d[0]]=j;
}
d[d[0]=1]=rig[i][m]=m;
for(j=m-1;j>=1;j--)
{
while(d[0]>0&&b[i][d[d[0]]]>=b[i][j])d[0]--;
rig[i][j]=(d[0])?(d[d[0]]-1):m;d[++d[0]]=j;
}
for(j=1;j<=m;j++)if(b[i][j])ans=max(ans,b[i][j]*(rig[i][j]-lef[i][j]+1));
}
return (ans>=k)?ans:0;
}
int main(){
int t,i,j;
scanf("%d",&t);
while(t--){
scanf("%d%d%d",&n,&m,&k);
for(i=1;i<=n;i++){
for(j=1;j<=m;j++)scanf("%d",&a[i][j]);
}
int l=0,r=1000000000;
while(l+1<r){
int mid=(l+r)/2;
if(solve(mid))l=mid;
else r=mid;
}
if(solve(r))l=r;
printf("%d %d\n",l,solve(l));
}
return 0;
}