【DP】【单调栈】question 题解

本文介绍了如何利用动态规划(DP)和单调栈解决一个01矩阵中1覆盖的最大矩形面积问题。通过统计每个位置的高度,并运用单调栈进行维护,可以有效地遍历矩阵并找到最大面积。

给一个01矩阵,求1覆盖的最大矩形面积。

统计每一个位置高度,单调栈维护,顺着跑一遍。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define INF 2147483647
#define LL long long
#define clr(x) memset(x, 0, sizeof x)
#define digit (ch <  '0' || ch >  '9')

using namespace std;

template <class T> inline void read(T &x) {
    int flag = 1; x = 0;
    register char ch = getchar();
    while( digit) { if(ch == '-')  flag = -1; ch = getchar(); }
    while(!digit) { x = (x<<1)+(x<<3)+ch-'0'; ch = getchar(); }
    x *= flag;
}

const int maxn = 1005;
int n,m,ans,st[maxn],ls[maxn],mp[maxn][maxn],up[maxn][maxn];

int main() {
    freopen("question.in","r",stdin);
    freopen("question.out","w",stdout);
    read(n); read(m);
    for(register int i = 1; i <= n; i++)
        for(register int j = 1; j <= m; j++) {
            read(mp[i][j]);
            if(mp[i][j]) up[i][j] = up[i-1][j]+1;
        }
    for(register int i = 1; i <= n; i++) {
        int tp = 0;
        for(register int j = 1; j <= m; j++)
            if(up[i][j] >= st[tp]) st[++tp] = up[i][j], ls[tp] = 1;
            else {
                int len = 0;
                while(tp && st[tp] > up[i][j]) len += ls[tp], ans = max(ans, len*st[tp--]);
                st[++tp] = up[i][j], ls[tp] = len+1;
            }
        int len = 0;
        while(tp) len += ls[tp], ans = max(ans, st[tp--]*len);
    }
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值