hdu 1506 单调栈求面积

点击打开链接

求出 高度h[i]向左和向右最远能扩展到的下标 
即利用单调栈 求出h[i]向左(右)最后一个不小于h[i]的下标

则以h[i]为高的面积为 h[i]*(R[i]-L[i]+1) 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;
const int N=1e6+20;
typedef long long ll;
ll h[N];
int L[N],R[N];//L[i] 高度h[i]向左最远能扩展到的下标 
//则以h[i]为高的面积为 h[i]*(R[i]-L[i]+1) 
int main()
{
	int n;
	while(cin>>n&&n)
	{
		stack <int> s;//单调栈 保存下标  
		for(int i=1;i<=n;i++)
		{
			scanf("%lld",&h[i]);
			while(!s.empty()&&h[s.top()]>h[i])
			{
				R[s.top()]=i-1;//(i-1):h[s.top()]向右最后一个不小于于它的下标 
				s.pop();
			}
			s.push(i);
		}
		while(!s.empty())
		{
			R[s.top()]=n;
			s.pop();
		}	
		
		for(int i=n;i>=1;i--)
		{
			while(!s.empty()&&h[i]<h[s.top()])
			{
				L[s.top()]=i+1;
				s.pop();
			}
			s.push(i);
		}
		while(!s.empty())
		{
			L[s.top()]=1;
			s.pop();
		}
		ll ans=0;
		for(int i=1;i<=n;i++)
		{
			ll res=(R[i]-L[i]+1)*h[i];
			ans=max(res,ans);
		}
		cout<<ans<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值