第一周任务Largest Submatrix of All 1’s

限于喜欢 提交于 2019-11-30 16:14:46
Largest Submatrix of All 1’s
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 9512   Accepted: 3406
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

Source


思路:
这道题是二维数组,跟上一道题多了一维,那么我们就一行遍历,求一行中最大的矩形,再行遍历的时候就更新最大矩形面积。
 

代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
const int maxn = 2e3+10;
int a[maxn][maxn];
int L[maxn],R[maxn]; 
int st[maxn];
int main(){
    int m,n;
    while(scanf("%d%d",&m,&n)!=EOF){
        for(int i=0;i<=n;i++)
            a[0][i] = 0;
        for(int i=1;i<=m;i++){
            for(int j=0;j<n;j++){
                scanf("%d",&a[i][j]);
                if(a[i][j]!=0)
                    a[i][j] = a[i][j] +a[i-1][j]; //这里是关键
            }
        }    
                
        int res = 0;
        for(int i=1;i<=m;i++){
            memset(st,0,sizeof(st));
            int t = 0;
            for(int j=0;j<n;j++){ 
                while(t>0&&a[i][st[t-1]]>=a[i][j]) t--;
                L[j] = t==0?0:(st[t-1]+1);
                st[t++] = j;  
            }
            t=0;
            for(int j = n-1;j>=0;j--){
                while(t>0&&a[i][st[t-1]]>=a[i][j]) t--;
                R[j] = t==0?n:(st[t-1]);
                st[t++] = j;
            }
            for(int j=0;j<n;j++){
                res=max(res,a[i][j]*(R[j]-L[j]));
            }
        }        
        cout<<res<<endl;
    }
    return 0;
}

 

 
 
 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!