基准时间限制:1 秒 空间限制:131072 KB 分值: 80
难度:5级算法题
给出1个M*N的矩阵M1,里面的元素只有0或1,找出M1的一个子矩阵M2,M2中的元素只有1,并且M2的面积是最大的。输出M2的面积。
Input
第1行:2个数m,n中间用空格分隔(2 <= m,n <= 500) 第2 - N + 1行:每行m个数,中间用空格分隔,均为0或1。
Output
输出最大全是1的子矩阵的面积。
Input示例
3 3 1 1 0 1 1 1 0 1 1
Output示例
4
思路:
①首先我们O(n^2)预处理出H【i】【j】,表示以位子(i,j)向上连续1的个数。
②那么我们O(n)枚举每一行,那么每一列的连续的1就在数组H【i】【j】中,我们考虑用单调栈维护两个数组L【j】以及R【j】,表示我们以位子j作为起点,能够向左拓展最远的位子和向右拓展的最远的位子,使得【L【j】,R【j】】区间内所有的H【i】【j】都大于等于H【i】【当前位子】;
③对于答案,我们维护Max((R【j】-L【j】+1)*【i】【j】)即可。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int a[2060][2060];
int h[2060][2060];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
for(int j=1;j<=m;j++)
{
for(int i=1;i<=n;i++)
{
if(a[i][j]==1)
h[i][j]=h[i-1][j]+1;
else h[i][j]=0;
}
}
int ans=0;
for(int i=1;i<=n;i++)
{
int L[2060],R[2060];
stack<int>s;
for(int j=1;j<=m;j++)
{
L[j]=0;
if(s.size()==0)
{
s.push(j);L[j]=j;
}
else
{
while(s.size()>0&&h[i][s.top()]>=h[i][j])s.pop();
if(s.size()==0)L[j]=1;
else L[j]=s.top()+1;
s.push(j);
}
}
while(!s.empty())
{
s.pop();
}
for(int j=m;j>=1;j--)
{
R[j]=m;
if(s.size()==0)
{
s.push(j);R[j]=j;
}
else
{
while(s.size()>0&&h[i][s.top()]>=h[i][j])s.pop();
if(s.size()==0)R[j]=m;
else R[j]=s.top()-1;
s.push(j);
}
}
for(int j=1;j<=m;j++)
{
ans=max(ans,(R[j]-L[j]+1)*h[i][j]);
}
}
printf("%d\n",ans);
}
}