Description
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
Source
POJ Founder Monthly Contest – 2008.01.31, xfxyjwf
虽然题目是二维的,但是仍然可以转化成单调栈来做。
用一个数组保存每一个0,1值,用另一个数组保存每一行的数的某一列以上所含的连续1的值
再用单调栈的想法就可以顺利解决了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAX_N 2005
using namespace std;
int a[MAX_N][MAX_N],b[MAX_N][MAX_N];//b数组用来存每一行累计连续1的值
int l[MAX_N],r[MAX_N];//每一行的
int main()
{
int m,n;
while(~scanf("%d%d",&n,&m))
{
memset(b,0,sizeof(b));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j])
{
if(b[i-1][j])
b[i][j]=b[i-1][j]+1;
else
b[i][j]=1;
}
else b[i][j]=0;
}
}
int maxn=-1;
for(int i=1;i<=n;i++)
{
l[0]=0,r[n+1]=0;
for(int j=1;j<=m;j++)
{
int k=j-1;
while(k>0&&b[i][j]<=b[i][k]) k=l[k]-1;
l[j]=++k;
}
for(int j=m;j>=1;j--)
{
int k=j+1;
while(k<m+1&&b[i][j]<=b[i][k]) k=r[k]+1;
r[j]=--k;
}
for(int j=1;j<=m;j++)
{
int s=(r[j]-l[j]+1)*b[i][j];
if(s>maxn) maxn=s;
}
}
printf("%d\n",maxn);
}
return 0;
}