HDU1506 Largest Rectangle in a Histogram (单调栈)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1506

题意:
求最大矩形面积

分析:
ll[i]表示i能往左延伸几步
rr[i]表示i能往右延伸几步

分别正序、逆序跑一遍单调栈即可得到ll,rr;
ans=max(ans,(ll[i]+rr[i]+1)*a[i]);

代码:

#include 
#define Pii pair
using namespace std;
typedef long long ll;
const int tmax=1e5+5;
ll a[tmax],lle[tmax],rr[tmax],n;
stack ST;
int main()
{
    int i;
    while(scanf("%I64d",&n)==1&&n>0)
    {
        memset(lle,0,sizeof(lle));
        memset(rr,0,sizeof(rr));
        for(i=1;i<=n;i++)
            scanf("%I64d",&a[i]);
        while(!ST.empty()) ST.pop();
        for(i=1;i<=n;i++)
        {
            while(!ST.empty()&&ST.top().first>=a[i])
            {
                lle[i]+=lle[ST.top().second]+1;
                ST.pop();
            }
            ST.push(Pii(a[i],i));
        }
        while(!ST.empty()) ST.pop();
        for(i=n;i>=1;i--)
        {
            while(!ST.empty()&&ST.top().first>a[i])
            {
                rr[i]+=rr[ST.top().second]+1;
                ST.pop();
            }
            ST.push(Pii(a[i],i));
        }
        ll ans=0;
        for(i=1;i<=n;i++)
            ans=max(ans,a[i]*(lle[i]+rr[i]+1));
        printf("%I64d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(单调栈与单调队列)