POJ2559 Largest Rectangle in a Histogram

这道题一看我们可以发现一个木桶原理,只要有一个短的,长的就没用了,我们就可以维护一个单调栈,如果碰到比前面小的,就直接进行统计和修改,最后再设n+1个矩形高度为0来统计,注意清零

#include<bits/stdc++.h>
using namespace std;
int st[100005],w[100005],s[100005],top,a[100005],n;
long long ans;
int main(){
    while(scanf("%d",&n)==1&&n){
        int k;
        for(int i=1;i<=n;i++)
         scanf("%d",&a[i]);
        top=a[n+1]=0;//巧设
        ans=0;
        for(int i=1;i<=n+1;i++){
            if(a[i]>s[top])
             w[++top]=1,s[top]=a[i];//单调性
            else{
             int wid=0;
             while(s[top]>a[i]){
                 wid+=w[top];
                 ans=max(ans,(long long)wid*s[top]);//统计
                 top--; 
             }
             s[++top]=a[i];w[top]=wid+1;
            }
        }
        cout<<ans<<endl;
    }
}

 

posted @ 2019-08-17 21:34  Coder_cjh  阅读(112)  评论(0编辑  收藏  举报