poj 3494 Largest Submatrix of All 1’s 单调栈/DP迭代法

题意:给出一个m*n的01矩阵,问在系数全为1的子矩阵中 系数和的最大值。

解法:DP中的迭代法,或者单调栈。

不论哪种方法核心都是对于每个高度为h的矩形,找到最左高度大于等于它的位置,和最右的位置。



#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 2000   ;


struct Node
{
    int h;
    int le;
};
int n,m,ans;
int h[maxn+10];

Node sta[maxn+10];
int main()
{
   while(~scanf("%d%d",&m,&n))
   {
       int x,ans=0;
       memset(h,0,(n+1)*sizeof h[0]);
       for1(i,m)
       {
           int top=0;
           for1(j,n)
          {
             scanf("%d",&x);
             if(!x) h[j]=0;
             else h[j]++;

             if(top&&sta[top].h>h[j])
             {
                while(top&&sta[top].h>h[j])
                {
                    ans=max(ans,  sta[top].h*(j-sta[top].le) );
                    top--;
                }
                sta[++top].h=h[j];
             }
             else
             {
                 sta[++top].h=h[j];
                 sta[top].le=j;
                if(top>=2&&sta[top-1].h==sta[top].h ) sta[top].le=sta[top-1].le;
             }
          }
          while(top)
          {
             ans=max(ans,sta[top].h*( n+1- sta[top].le) );
              top--;
          }
       }
        printf("%d\n",ans);

   }

   return 0;
}

/*
4 4
1 0 0 0
1 1 1 1
0 1 1 1
1 0 0 1

*/


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值