POJ

Largest Submatrix of All 1’s

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 ≤ mn ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on mlines 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


很巧妙的方法。把图拆成一行行来做,分别求以每行为底的最大矩形面积,类似lc课后辅导。最后比较出最大值即可。

#include<stdio.h>
#include<stack>
using namespace std;

int a[2005][2005];
int l[2005],r[2005];

int main()
{
    int n,m,max,i,j;
    while(~scanf("%d%d",&n,&m)){
        max=0;
        for(i=1;i<=n;i++){
            for(j=1;j<=m;j++){
                scanf("%d",&a[i][j]);
                if(a[i][j]==1) a[i][j]+=a[i-1][j];
            }
        }
        for(i=1;i<=n;i++){
            stack<int> s;
            for(j=1;j<=m;j++){
                while(s.size()&&a[i][s.top()]>=a[i][j]) s.pop();
                l[j]=s.size()==0?1:s.top()+1;
                s.push(j);
            }
            while(s.size()){
                s.pop();
            }
            for(j=m;j>=1;j--){
                while(s.size()&&a[i][s.top()]>=a[i][j]) s.pop();
                r[j]=s.size()==0?m:s.top()-1;
                s.push(j);
            }
            for(j=1;j<=m;j++){
                if(a[i][j]*(r[j]-l[j]+1)>max) max=a[i][j]*(r[j]-l[j]+1);
            }
        }
        printf("%d
",max);
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/yzm10/p/7234485.html