2017省选拔(二)poj3494 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 ≤ m,n ≤ 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
题目大意:给出一个01矩阵,求出全是1的矩阵的面积。

题解:既然让求面积,无非就是长乘以宽嘛。那么目标就是去找长和宽就行了。先看看长吧。这里长就是1矩阵的高度,这个我可以预处理出来,就是对每一行的1的高度是上一行中的高度+1。当此位置是0的时候高度就是0喽。这样的话,比如位置(i,j),如果(i,j)的是1的话,他所求得高度是以该行为最低边向上的高度。然后我对每一行再求以(i,j)为矩阵的高的宽度。求宽度就用单调栈就可以了。

ps:如果是单调栈的初学者,建议先看一下这个题 http://blog.csdn.net/txgang/article/details/70049705

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>

using namespace std;

int mp[2222][2222];
int dp[2222][2222];
int l[2222][2222],r[2222][2222];

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=m; j++)
            {
                scanf("%d",&mp[i][j]);
                if(mp[i][j])
                {
                    dp[i][j]+=dp[i-1][j]+1;
                }
                else dp[i][j]=0;
            }
        }
        for(int i=1; i<=n; i++)
        {
            dp[i][0]=-1;
            dp[i][m+1]=-1;
        }
        int mx=0;
        stack<int>s;
        while(!s.empty())s.pop();
        for(int i=1; i<=n; i++)
        {
            while(!s.empty())s.pop();
            s.push(0);
            for(int j=1; j<=m; j++)
            {
                int k;
                for(k=s.top(); dp[i][j]<=dp[i][k]; k=s.top())
                {
                    s.pop();
                }
                l[i][j]=k+1;
                s.push(j);
            }
            while(!s.empty())s.pop();
            s.push(m+1);
            for(int j=m; j>=1; j--)
            {
                int k;
                for(k=s.top(); dp[i][j]<=dp[i][k]; k=s.top())
                {
                    s.pop();
                }
                r[i][j]=k-1;
                s.push(j);
            }
            int sum=0;
            for(int j=1; j<=m; j++)
            {
                sum=dp[i][j]*(r[i][j]-l[i][j]+1);
                mx=max(mx,sum);
            }
        }
        printf("%d\n",mx);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值