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;
}

猜你喜欢

转载自blog.csdn.net/qq_39021458/article/details/81335087
今日推荐