1. 程式人生 > >單調棧模板【poj2559】

單調棧模板【poj2559】

單調棧,就是具有單調性的棧。

本題你只要維護棧的單調性即可。每個矩形入棧時,判斷它的高度是否大於等於棧頂矩形的高度,如果滿足,則直接入棧。否則就向前找,一邊出棧一邊記錄寬度,計算面積。知道找到第一個不滿足條件的位置,然後將當前高度入棧。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int n,top,cnt,h[100035],p[100035],w[100035];
long long ans;
int main()
{
	scanf("%d",&n);
	while (n)
	{
		top=0;
		ans=0LL;
		for (int i=1;i<=n+1;i++) 
		{
			if (i!=n+1) scanf("%d",&h[i]);else h[i]=0;
			if (h[i]>=p[top]) p[++top]=h[i],w[top]=1;
			else
			{
				int wide=0;
				while (h[i]<p[top]&&top>0)
				{
					wide+=w[top];
					ans=max(ans,(long long)wide*p[top]);
					top--;
				}
				p[++top]=h[i];w[top]=wide+1;
			}
		}
		printf("%lld\n",ans);
		scanf("%d",&n);
	}
}