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
题意:
找出矩阵中最大的矩形
跟HDU1506那题差不多 利用单调栈 找出左右两边的边界 然后求出矩形的面积就好
然后记录最大的面积
不过不一样的是 这个需要进行m次 我的代码里面写的nm跟题目是反过来的..
因为习惯了看 n是行 m是列
要先处理了矩阵往下的连续高度 然后保存下来 再开始找边界
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
using namespace std;
const int N=2e3+10;
int Map[N][N],h[N][N];
int L[N],R[N],st[N];
int main()
{
int m,n;
while (~scanf("%d%d",&n,&m))
{
for (int i=0 ; i<n ; i++)
for (int j=0 ; j<m ; j++)
scanf("%d",&Map[i][j]);
for (int i=0 ; i<m ; i++)
{
int high=0;
for (int j=n-1 ; j>=0 ; j--)//从底层开始处理高度 记录当前点往下连续的高度
{
if (Map[j][i]==1)
high++;
else
high=0;
h[j][i]=high;
}
}
int ans=0;
for (int i=0 ; i<n ; i++)
{
int pos=0;
for (int j=0 ; j<m ; j++)//扫左边的最大值
{
while (pos>0 && h[i][st[pos-1]]>=h[i][j])
pos--;
L[j]=pos==0?0:st[pos-1]+1;
st[pos++]=j;
}
pos=0;
for (int j=m-1 ; j>=0 ;j--)//扫右边的最大值
{
while (pos>0 && h[i][st[pos-1]]>=h[i][j])
pos--;
R[j]=pos==0?m-1:st[pos-1]-1;
st[pos++]=j;
}
for (int j=0 ; j<m ; j++)
if (h[i][j]*(R[j]-L[j]+1)>ans)
ans=h[i][j]*(R[j]-L[j]+1);
}
printf("%d\n",ans);
}
return 0;
}