POJ2559Largest Rectangle in a Histogram(单调栈)

传送门

题目大意:给出一个柱状统计图,该统计图由多个宽度为1高度不一的矩形构成,问图中包含最大的矩形面积是多少。

题解:枚举每一个小矩形的高度,以它的高度为所求矩形高度向左右扩展,可知到左边第一个小于它和右边第一个小于它的矩形时扩展结束。
所以用单调栈求每个元素左边第一个小于它和右边第一个小于它的元素。多组数据,别忘更新ans。。。

#include<iostream>
#include<stack>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100009
#define LL long long
using namespace std;

int n;

stack<LL>s;

LL ans;
LL l[N],r[N],a[N];

int main()
{
	while(scanf("%d",&n)&&n)
	{
		while(!s.empty()) s.pop();
		s.push(0);
		ans=0;//**忘了更新答案 
		a[0]=a[n+1]=0;//忘了设置端点。。。 
		for(int i=1;i<=n;i++)
		{
			//scanf("%lld",&a[i]);
			cin>>a[i];
			LL x=s.top();
			while(a[x]>=a[i]&&!s.empty())
			{
				s.pop();
				if(!s.empty())x=s.top();
			}
			l[i]=x+1;
			s.push(i); 
		}
		while(!s.empty()) s.pop();
		s.push(n+1);
		for(int i=n;i>=1;i--)
		{
			LL x=s.top();
			while(a[x]>=a[i]&&!s.empty())
			{
				s.pop();
				if(!s.empty())x=s.top();
			}
			r[i]=x-1;
			ans=max(ans,a[i]*(r[i]-l[i]+1));
			s.push(i);
		}
/*		for(int i=1;i<=n;i++)
		{
		//	cout<<i<<" "<<a[i]<<"  "<<l[i]<<"  "<<r[i]<<endl;
			ans=max(ans,a[i]*(r[i]-l[i]+1));
		}*/
		cout<<ans<<endl;
	}
	return 0;
} 
posted @ 2020-06-24 20:35  ANhour  阅读(171)  评论(0编辑  收藏  举报