SSL_3494 Largest Submatrix of All 1’s
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
题目翻译+分析
`
题目意思差不多就是给出一个由0和1组成的矩阵,求出最大的元素全为1的子矩阵的大小。
这道题跟poj 2559差不多,只不过从一维变成了二维,而且底部也没有对齐。
如何解决呢?我们可以采用降维战术,一行一行地压下去,每压一行就做一次计算算出当前最大矩形。细节很多,本蒟蒻调了快1个小时才Accepted
代码实现
#include<iostream>
#include<cstdio>
#include<cstring>
#define sco 3000
using namespace std;
int st[sco],top,n,m,a[sco],ans,to,tmp,b[sco];
int mp[sco][sco];
int solve(){
int an=0;top=0;memset(st,0,sizeof(st));tmp=0;to=0; //初始化很重要
for(int i=0;i<=m;i++){
if(top==0 or a[st[top]]<=a[i]){
st[++top]=i;
}
else{
while(top>0 and a[i]<a[st[top]]){
to=st[top];
top--;
tmp=(i-to)*a[to];
if(tmp>an) an=tmp;
}
st[++top]=to;
a[to]=a[i];
}
}
return an;
}
int main(){
while(~scanf("%d%d",&n,&m)){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b)); //还有这里也要初始化
ans=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&mp[i][j]);
if(mp[i][j]==1){ //把二维数组降为一维数组
b[j]=b[j]+1;
}
else{
b[j]=0;
}
a[j-1]=b[j]; //我用的算法统计时会改变原数组,需要另外备份与调整位置
}
ans=max(ans,solve()); //统计答案
}
printf("%d\n",ans);
}
return 0;
}