Poj 2559 Largest Rectangle in a Histogram(单调栈)

题目地址:http://poj.org/problem?id=2559

思路:

方法一:设置一单调栈,栈中元素按高度依次递增。则对于新加入的元素,若当前高度大于栈顶元素高度,则直接入栈;否则,不断退栈直到栈顶元素高度小于当前元素高度(因前一高度已不能继续延续到当前高度)并将更新当前元素宽度,入栈。退栈过程中不断更新最大值:栈中元素(2,1),当前元素(1,1)此时退栈并且将退栈元素宽度累加作为当前元素宽度,则栈中元素变为(1,2);若栈中元素为(1,2)、(4,1)、(5,1),当前元素为(1,1),则退栈过程为(1,2)、(4,2);(1,4);(1,5)。若处理完后栈中元素不为空,按同样方法直到栈为空并不断更新最大值。

方法二:设置l[i]代表a[i]作为最小值向左最远的位置,r[i]代表a[i]作为最小值向右最远的位置。则ans=max{a[i]*(r[i]-l[i]+1)}。更新l[i]时,当a[l[i]-1]>=a[i]时,不断将l[i]置为l[l[i]-1];当a[r[i]+1]>=a[i]时,不断将r[i]置为r[r[i]+1]。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+50;
struct Node
{
    int h,w;
};
int n;
Node S[maxn];
int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        int top=0;
        LL ans=0;
        for(int i=1;i<=n;i++)
        {
           int h,tmp=0;
           scanf("%d",&h);
           while(top>0&&S[top].h>=h)
           {
               ans=max(ans,(LL)S[top].h*(S[top].w+tmp));
               tmp+=S[top].w;
               top--;
           }
           top++,S[top].h=h;
           S[top].w=tmp+1;
        }
        int tmp=0;
        while(top)
        {
            ans=max(ans,(LL)S[top].h*(S[top].w+tmp));
            tmp+=S[top].w;
            top--;
        }
        printf("%lld\n",ans);
    }
    return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+50;
int n;
int l[maxn];
int r[maxn];
int a[maxn];
int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            l[i]=r[i]=i;
        }
        a[0]=a[n+1]=-1;
        for(int i=1; i<=n; i++)
        {
            while(a[l[i]-1]>=a[i])
            {
                l[i]=l[l[i]-1];
            }
        }
        for(int i=n; i>=1; i--)
        {
            while(a[r[i]+1]>=a[i])
            {
                r[i]=r[r[i]+1];
            }
        }
        LL ans=0;
        for(int i=1; i<=n; i++)
        {
            ans=max(ans,(LL)a[i]*(r[i]-l[i]+1));
        }
        printf("%lld\n",ans);
    }
    return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值