《算法竞赛进阶指南》0x11栈 单调栈求矩形面积 POJ2559

题目链接:http://poj.org/problem?id=2559

典型问题,就是有一个地方要注意,用数组模拟栈的时候要判断栈是否为空才能弹出元素,否则的话,设置一个st[0]=-1,这样矩形高度是0的时候就会自动判断栈空。

代码如下:

#include<iostream>
#include<cstdio>
using namespace std;
#define maxn 100010
typedef long long ll ;
int st[maxn],h[maxn],w[maxn];
int n;
int main(){
    while(scanf("%d",&n) && n){
        int top=0;
        ll ans=0;
        for(int i=0;i<n;i++)scanf("%d",&h[i]);
        st[top]=-1;
        for(int i=0;i<n;i++){
            if(h[i]>st[top])st[++top]=h[i],w[top]=1;
            else {
                ll width=0;
                while( st[top] >= h[i]){//将所有比当前矩形高的矩形退栈,并计算最大值 
                    width+=w[top];
                    ans=max(ans,1ll*width*st[top]);
                    top--;
                }
                st[++top]=h[i],w[top]=width+1;
            }
        }
        ll width=0;
        while(top){        //最后将栈中单调的矩形退栈    
            width+=w[top];
            ans=max(ans,1ll*width*st[top]);
            top--;
        } 
        cout<<ans<<endl; 
    }
} 

 

posted @ 2020-06-17 10:17  WA自动机~  阅读(165)  评论(0编辑  收藏  举报