题目
Given a m-by-n (0,1)-matrix, of all its submatrices of all 1’s which is the largest? By largest we mean that the submatrix has the most elements.
Input
The input contains multiple test cases. Each test case begins with m and n (1 ≤ m, n ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on m lines each with n numbers. The input ends once EOF is met.
Output
For each test case, output one line containing the number of elements of the largest submatrix of all 1’s. If the given matrix is of all 0’s, output 0.
Sample Input
2 2
0 0
0 0
4 4
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0
Sample Output
0
4
思路:一行一行遍历,对每一行求矩形面积(如下图)
solve函数详解戳这里[https://blog.csdn.net/w_m_w_m_w_m_w_m/article/details/97931507]
对主函数中if语句的解释
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n,h[2010]={0},l[2010],r[2010],st[2010];
long long c=0;
long long solve()
{
int t=0;
for(int i=0;i<n;i++)
{
while(t>0&&h[st[t-1]]>=h[i])
t--;
l[i]=t==0?0:(st[t-1]+1);
st[t++]=i;
}
t=0;
for(int i=n-1;i>=0;i--)
{
while(t>0&&h[st[t-1]]>=h[i])
t--;
r[i]=t==0?(n-1):(st[t-1]-1);
st[t++]=i;
}
for(int i=0;i<n;i++)
c=max(c,(long long)h[i]*(r[i]-l[i]+1));
return c;
}
int main()
{
int m;
while(scanf("%d%d",&m,&n)!=EOF)
{
c=0;
long long ma=0;
for(int i=0;i<m;i++) //按行遍历
{
for(int j=0;j<n;j++) //遍历行中的每一个元素
{
if(i!=0&&h[j]!=0) //不是第一行且这个位置对应的上一行的元素不为零
{
int ch=h[j];
scanf("%d",&h[j]);
if(h[j]!=0) h[j]=ch+1;
}
else scanf("%d",&h[j]);
}
ma=max(ma,solve());
}
printf("%lld\n",ma);
}
return 0;
}