0
点赞
收藏
分享

微信扫一扫

Largest Submatrix of All 1’s (单调队列)

Problem 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

<p>The input contains multiple test cases. Each test case begins with <i>m</i> and <i>n</i> (1 ≤ <i>m</i>, <i>n</i> ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on <i>m</i> lines each with <i>n</i> numbers. The input ends once EOF is met.</p>


Output

<p>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.</p>


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



题目大概:

有一个只有1和0组成的矩形,问最大的矩形(全部由1组成的矩形)的面积是多少。

思路:

这道题刚开始是没思路的,后来被人提醒,想起在学习dp时,曾经遇到过矩形求最大n子段和问题,用的状态压缩,这里也可以用这个,把矩形压缩成一条线,然后的过程,就是例题求矩形面积了,不过这里要求n遍,因为每行都要压缩,每行都要求一遍。于是这个题变得就简单多了,这个题值得说一下的是,这个题我为了防止TLE,输入输出用的scanf,printf。但是后来发现这样做会超时,但是用cin,cout,反而通过了,这不符合常理啊。这里一定要记住,有时间好好研究研究,这到底是怎么回事。

代码:



#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n,m;
int map[2002][2002];
int l[2002],r[2002],q[2002];

int getl(int j)
{
q[0]=0;
int le=0,ri=1;
for(int i=1;i<=n;i++)
{
while(le<ri&&map[j][i]<=map[j][q[ri-1]])ri--;
l[i]=i-q[ri-1]-1;
q[ri++]=i;

}
}

int getr(int j)
{ q[0]=n+1;
int le=0,ri=1;
for(int i=n;i>=1;i--)
{
while(le<ri&&map[j][i]<=map[j][q[ri-1]])ri--;
r[i]=q[ri-1]-i-1;
q[ri++]=i;

}
}
int main()
{
while(cin>>n>>m)
{ memset(map,0,sizeof(map));
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{ int qq;
scanf("%d",&qq);
if(qq==1)
{
map[i][j]=map[i-1][j];
map[i][j]++;;
}
}
}
int su=0;
for(int i=1;i<=m;i++)
{ int sum=0;
getl(i);
getr(i);
for(int j=1;j<=n;j++)
{
int sun=(l[j]+r[j]+1)*map[i][j];
if(sum<sun)sum=sun;
}
if(su<sum)su=sum;
}
cout<<su<<endl;

}


return 0;
}





举报

相关推荐

0 条评论