POJ 2559 Largest Rectangle in a Histogram【单调栈】

题意:给你一堆紧挨着的高度不定,长度为1的矩形,让你求最大矩形面积.
这里写图片描述
分析:
用单调栈维护一个最长非递减序列,遇到不满足的情况,直接出栈并计算面积(这个面积以pop的高度为高度,长取最长).

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
using namespace std;

typedef long long LL;
typedef pair<LL, LL> pii;
stack<pii> s;

int main() {
    LL n, k;
    while(scanf("%lld", &n) && n) {
        while(!s.empty()) s.pop();
        scanf("%lld", &k);
        s.push(pii(k, 1LL));
        LL ans = 0, len;
        for(int i = 0; i < n - 1; ++i) {
            scanf("%lld", &k);
            if(k >= s.top().first) {
                s.push(pii(k, 1LL));
                continue;
            }
            len = 0;
            while(s.top().first > k) {
                len += s.top().second;//注意长度的更新 
                if(ans < s.top().first * len) {
                    ans = s.top().first * len;
                }
                s.pop();
                if(s.empty()) break;
            }
            s.push(pii(k, len + 1LL));
        } 
        len = 0;
        while(!s.empty()) {
            len += s.top().second;;
            if(ans < s.top().first * len) {
                ans = s.top().first * len;
            }
            s.pop();
        }
        printf("%lld\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值