HDU-Largest Rectangle in a Histogram-1506 单调栈

Posted the-way-of-cas

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-Largest Rectangle in a Histogram-1506 单调栈相关的知识,希望对你有一定的参考价值。

连接:http://acm.hdu.edu.cn/showproblem.php?pid=1506

题意:给一个柱状图,每个小矩形宽为1,求这个柱状图最大子矩形的面积

思路:用单调栈求出每个小矩形所能组成最大矩形的左宽和有宽,分别存在l[i] , r[i]数组里,然后 ans = max( h[i] * ( r[i] - l[i] )

注意:int * int 结果可能超过2^32

代码:

#include <iostream>
#include <algorithm>
#define ll long long
#define maxn 100000+100
//#define scanf scanf_s

using namespace std;

int n;
int h[maxn];
int l[maxn], r[maxn];
int st[maxn];

void solve() {
    int t = 0;
    for (int i = 0; i < n; i++)
    {
        while (t > 0 && h[st[t - 1]] >= h[i]) t--;
        l[i] = t == 0 ? 0 : (st[t - 1] + 1);
        st[t++] = i;
    }
    t = 0;
    for (int i = n-1; i >= 0; i--)
    {
        while (t > 0 && h[st[t - 1]] >= h[i]) t--;
        r[i] = t == 0 ? n : st[t - 1];
        st[t++] = i;
    }
    ll res = 0;
    for (int i = 0; i < n; i++)
    {
        res = max(res, 1ll*h[i] * (r[i] - l[i]));
    }
    printf("%lld
", res);
}

int main() {
    while (scanf("%d", &n) && n) {
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &h[i]);
        }
        solve();
    }
    return 0;
}

 

以上是关于HDU-Largest Rectangle in a Histogram-1506 单调栈的主要内容,如果未能解决你的问题,请参考以下文章

84. Largest Rectangle in Histogram *HARD* 柱状图求最大面积 85. Maximal Rectangle *HARD*

Largest Rectangle in Histogram及二维解法

Largest Rectangle in Histogram

Largest Rectangle in Histogram

Largest Rectangle in Histogram

Largest Rectangle in a Histogram