1. 程式人生 > >POJ2104 最大矩形面積 單調棧

POJ2104 最大矩形面積 單調棧

題目是英文的…這裡簡單描述一下,就是給你n個寬度1的矩形,然後連在一排,求新組成的圖形中的最大矩形.
單調棧維護一個高度單調遞增的棧,每個新數經來的時候要是比棧頂元素小的話就彈出棧頂元素直到不能再彈為止.過程中更新答案。最後清棧更新答案.

#include<stdio.h>
#include<algorithm>
#define dnt long long
using namespace std;
const int maxn=100005;
dnt ans,h[maxn],c[maxn],s[maxn],tmp;
int top,n;
inline const dnt read(){
    register
int f=1,x=0; register char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();} return f*x; } int main(){ while(n=read()){ ans=0,top=0; for(register int i=1;i<=n;i++) h[i]=read(); for
(register int i=1;i<=n;i++){ tmp=0; while(top&&h[i]<=h[s[top]]){ ans=max(ans,h[s[top]]*(c[s[top]]+tmp)); tmp+=c[s[top]]; top--; } ++top; s[top]=i; c[i]=tmp+1; } tmp=0
; while(top){ ans=max(ans,h[s[top]]*(c[s[top]]+tmp)); tmp+=c[s[top]]; top--; } printf("%lld\n",ans); } }