题目链接
MINSUB - 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
题意:
给定一个由非负数组成的矩阵M,和一个整数K,对于矩阵M的子矩阵M’,定义min(M’)为M'矩阵中元素的最小值。
我们需要找出这样一个子矩阵,该矩阵的面积至少为K,且min(M’)最大化。面积的定义为该矩阵的行数*列数。求出min(M'),并给出使得min(M')为该值时面积的最大值。
题解:
这类问题都是可以二分答案的。把小于二分值的位置设为0,其他设为1,那么问题就变成了求全为1的子矩阵的最大面积,这件事情可以用单调栈搞,可以预处理出每个点(i,j)的左边有多少个连续的1(记为f[i][j]),然后枚举每一列,那么这一列就可以类似与单调栈一样处理算出能上下延伸多少,做法和一位数组的单调栈一样。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <stack>
using namespace std;
const int maxn = 1e3 + 5;
int maze[maxn][maxn], val[maxn][maxn], l[maxn];
int n, m, k;
int check(int x)
{
memset(val, 0, sizeof(val));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
if(maze[i][j] >= x) val[i][j] = 1;
if(val[i][j]) val[i][j] = val[i][j-1] + 1;
}
int ans = -1;
for(int j = 1; j <= m; j++)
{
stack<int> s;
val[n+1][j] = -1;
for(int i = 1; i <= n+1; i++)
{
while(s.size() && val[s.top()][j] >= val[i][j])
{
ans = max(ans, (i-l[s.top()])*val[s.top()][j]);
s.pop();
}
l[i] = s.size() == 0 ? 1 : s.top()+1;
s.push(i);
}
}
return ans;
}
int main()
{
int t;
cin >> t;
while(t--)
{
scanf("%d%d%d", &n, &m, &k);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
scanf("%d", &maze[i][j]);
int l = 0, r = 1e9, mid, ans;
while(l <= r)
{
mid = (l+r)/2;
if(check(mid) >= k)
ans = mid, l = mid + 1;
else
r = mid - 1;
}
printf("%d %d\n", ans, check(ans));
}
return 0;
}