码迷,mamicode.com
首页 > 其他好文 > 详细

【单调栈】hdu1506 Largest Rectangle in a Histogram

时间:2017-01-15 23:53:33      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:http   namespace   main   存储   push   article   答案   stream   tac   

单调栈的介绍及一些基本性质

http://blog.csdn.net/liujian20150808/article/details/50752861

依次把矩形塞进单调栈,保持其单增,矩形中的元素是一个三元组,存储其位置,高度,以及以其为高度的情况下,大矩形的左边界最多扩展到哪里。

每次将新的元素塞进栈的时候,其左边界就是其左侧第一个小于它的矩形的位置+1。

然后,每个矩形出栈的时候,记录其右边界为当前往栈里面塞的矩形的位置-1,然后更新答案即可。

注意最后把所有的矩形出栈,更新答案。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
typedef long long ll;
struct data
{
	int l,h,p;
	data(const int &X,const int &Y,const int &Z)
	  {
	  	l=X;
	  	h=Y;
	  	p=Z;
	  }
	data(){}
};
stack<data>st;
int n,a[100010];
ll ans;
int main()
{
	while(1)
	  {
	  	scanf("%d",&n);
	  	if(!n)
	  	  break;
	  	ans=0;
		st.push(data(0,-1,0));
	  	for(int i=1;i<=n;++i)
	  	  scanf("%d",&a[i]);
	  	a[n+1]=-1;
	  	for(int i=1;i<=n+1;++i)
	  	  {
	  	  	while((!st.empty()) && a[i]<=st.top().h)
	  	  	  {
	  	  	  	ans=max(ans,(ll)(i-st.top().l)*(ll)st.top().h);
	  	  	  	st.pop();
	  	  	  }
	  	  	if(!st.empty())
	  	  	  st.push(data(st.top().p+1,a[i],i));
	  	  }
	  	cout<<ans<<endl;
	  }
	return 0;
}

【单调栈】hdu1506 Largest Rectangle in a Histogram

标签:http   namespace   main   存储   push   article   答案   stream   tac   

原文地址:http://www.cnblogs.com/autsky-jadek/p/6288176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!