Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 5726 | Accepted: 2150 | |
Case Time Limit: 2000MS |
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
题意:找到最大的全是1的子矩阵
思路:把1想象组成一个长方形的一部分。预处理出每个数向下延伸的矩形的高度,然后就是比较以每一行为底能得到的最大矩形面积。
就和POJ2559一样了。可以看这篇博客:http://blog.csdn.net/say_c_box/article/details/52013051
#include <cmath>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
using namespace std;
#define MAXN 2010
#define LEN 200010
#define INF 1e9+7
#define MODE 1000000
#define pi acos(-1)
#define g 9.8
typedef long long ll;
int n,m;
int h[MAXN][MAXN],a[MAXN][MAXN];
int l[MAXN],r[MAXN];
stack <int> ans;
long long solve(int j)
{
while(!ans.empty())
ans.pop();
for(int i=0;i<m;i++)
{
while(!ans.empty()&&h[j][ans.top()]>=h[j][i])
{
ans.pop();
}
if(ans.empty())
l[i]=0;
else
l[i]=ans.top()+1;
ans.push(i);
}
while(!ans.empty())
ans.pop();
for(int i=m-1;i>=0;i--)
{
while(!ans.empty()&&h[j][ans.top()]>h[j][i])
{
ans.pop();
}
if(ans.empty())
r[i]=n-1;
else
r[i]=ans.top()-1;
ans.push(i);
}
long long res=0;
for(int i=0;i<m;i++)
res=max(res,(long long )h[j][i]*(r[i]-l[i]+1));
return res;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
scanf("%d",&a[i][j]);
}
for(int i=0;i<m;i++){
if(a[n-1][i])
h[n-1][i]=1;
else
h[n-1][i]=0;
}
for(int i=n-2;i>=0;i--)
for(int j=0;j<m;j++)
{
if(a[i][j]==0)
h[i][j]=0;
else
h[i][j]=h[i+1][j]+1;
}
long long ans=0;
for(int j=0;j<n;j++)
{
ans=max(ans,solve(j));
}
printf("%I64d\n",ans);
}
}