HDU - 1506 Largest Rectangle in a Histogram

Posted y2823774827y

tags:

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

题目

HDU - 1506 Largest Rectangle in a Histogram

做法

(a_i)为最高高度,以(i)向左右扩展

找到(i)左边比(a_i)小的最右边的位置
找到(i)有边比(a_i)小的最左边的位置

简直是单调栈的模板题

My complete code

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<ctime>
#include<stack>
using namespace std;
typedef long long LL;
const LL maxn=200000;
inline LL Read(){
    LL x(0),f(1); char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')f=-1;c=getchar();
    }
    while(c>='0'&&c<='9')
        x=(x<<3)+(x<<1)+c-'0',c=getchar();
    return x*f;
}
LL n;
LL a[maxn],L[maxn],R[maxn];
stack<LL>sta;
int main(){
    while(scanf("%lld",&n)!=EOF&&n){
        for(LL i=1;i<=n;++i)
            a[i]=Read();
        while(sta.size())
            sta.pop();
        for(LL i=1;i<=n;++i){
            while(sta.size()&&a[sta.top()]>=a[i])
                sta.pop();
            if(sta.size())
                L[i]=sta.top()+1;
            else
                L[i]=1;
            sta.push(i);
        }
        while(sta.size())
            sta.pop();
        for(LL i=n;i>=1;--i){
            while(sta.size()&&a[sta.top()]>=a[i])
                sta.pop();
            if(sta.size())
                R[i]=sta.top()-1;
            else
                R[i]=n;
            sta.push(i);
        }
        LL ans(0);
        for(LL i=1;i<=n;++i)
            ans=max(ans,a[i]*(R[i]-L[i]+1));
        printf("%lld
",ans);
    }
    return 0;
}/*
*/

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

HDU1506 Largest Rectangle in a Histogram

HDU1506 Largest Rectangle in a Histogram (动规)

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

*HDU - 1506POJ - 2559Largest Rectangle in a Histogram(单调栈或动态规划)

hdu_1506:Largest Rectangle in a Histogram 单调栈

HDU - 1506 Largest Rectangle in a Histogram(dp)