[POJ 2559 Largest Rectangle in a Histogram] 单调栈

[POJ 2559 Largest Rectangle in a Histogram] 单调栈

题目链接[POJ 2559 Largest Rectangle in a Histogram]
题意描述:给定一个柱形图,总长度为N,每个区间长度为 h1,h2,,hn ,求在柱形图中的最大面积的矩形。
这里写图片描述
解题思路
点击查看单调栈的一些性质:《 [poj 2796 Feel Good] 单调栈
单调栈求出每个数向左向右能够拓展的最大区间,然后乘以区间长度就好了。

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

//#pragma comment(linker, "/STACK:1024000000,1024000000")

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)
#define fst             first
#define snd             second

typedef __int64 LL;
//typedef long long LL;
typedef pair<int, int> PII;

const int MAXN = 100000 + 5;
const int INF = 0x3f3f3f3f;
int N;
int H[MAXN], L[MAXN], R[MAXN];
struct SNode {
    int id, val;
    SNode () {}
    SNode (int id, int val) : id (id), val (val) {}
} tp;
stack<SNode> stk;
int main() {
#ifndef ONLINE_JUDGE
    FIN;
#endif // ONLINE_JUDGE
    while (~scanf ("%d", &N) && N) {
        int P = 0;
        for (int i = 1; i <= N; i++) {
            scanf ("%d", &H[i]);
        }
        for (int i = 1; i <= N; i++) {
            while (!stk.empty() && stk.top().val > H[i]) {
                tp = stk.top();
                R[tp.id] = i - 1;
                stk.pop();
            }
            stk.push (SNode (i, H[i]) );
        }
        while (!stk.empty() ) {
            tp = stk.top();
            R[tp.id] = N;
            stk.pop();
        }
        for (int i = N; i >= 1; i--) {
            while (!stk.empty() && stk.top().val > H[i]) {
                tp = stk.top();
                L[tp.id] = i + 1;
                stk.pop();
            }
            stk.push (SNode (i, H[i]) );
        }
        while (!stk.empty() ) {
            tp = stk.top();
            L[tp.id] = 1;
            stk.pop();
        }
        LL ans = -1;
        int l, r;
        for (int i = 1; i <= N; i++) {
            LL x = (LL) (R[i] - L[i] + 1) * H[i];
            if (x >= ans) {
                ans = x, l = L[i], r = R[i];
            }
        }
        printf ("%I64d\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值