Largest Submatrix of All 1’s@POJ 3494

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

 

题目分析:这个题一开始思路就偏了,搜索、DP都尝试了几次过不了,最后借助题解才发现应该用单调栈,而且思路也是很巧妙。

这个题做法类似于Restructuring Company@CodeForces 566D

只不过这个题要更为复杂一些,要分别在每一行上计算每一列最大的高度(即从该行开始往上数这一列最长的连续的1的个数),然后枚举找到最大值。

 

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <cstdio>
#include <stack>
#include <deque>
#include <set>
#include <cmath>
#include <map>
#define MAXN 2003
#define INF 0x3f3f3f3f
using namespace std;

int h[MAXN][MAXN]; //h[i][j]记录i行j列往上数连续1的个数,即高度
int l[MAXN]; 
int r[MAXN];
stack<int> s;

void left_min(int row,int col){
    while(!s.empty()) s.pop();
    for(int i=1;i<=col;++i){
        while(!s.empty() && h[row][i] <= h[row][s.top()]) s.pop();
        if(!s.empty()) l[i] = s.top();
        else l[i] = 0;
        s.push(i);
    }
}

void right_min(int row,int col){
    while(!s.empty()) s.pop();
    for(int i=col;i>=1;--i){
        while(!s.empty() && h[row][i] <= h[row][s.top()]) s.pop();
        if(!s.empty()) r[i] = s.top();
        else r[i] = col+1;
        s.push(i);
    }
}

int main(){
    int n,m;
    while(~scanf("%d%d",&n,&m)){
        int val;
        for(int i=1;i<=n;++i){
            for(int j=1;j<=m;++j){
                scanf("%d",&val);
                if(val) h[i][j] = h[i-1][j]+1; //如果是1,那么在前一行的基础上+1
                else h[i][j] = 0; //如果是0,清零
            }
        }
        int ans = 0;
        for(int i=1;i<=n;++i){
            left_min(i,m); //单调栈,从左往右找
            right_min(i,m); //从右往左找
            for(int j=1;j<=m;++j){
                if(ans < (r[j]-l[j]-1)*h[i][j]) ans = (r[j]-l[j]-1)*h[i][j];
            }
        }
        cout << ans << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值