单调栈

作用: 可以很方便地求出  某个数的左边或者右边  第一个比它大或者小的元素

 

实现: 当栈顶元素比要进栈的元素大,则弹出    (单调递增栈)

直到栈顶元素比他小为止

进栈

 

来源:https://user.qzone.qq.com/50222268/blog/1497969740

代码:

注意范围!!!

#include <cstdio>
#include <algorithm>
#include <stack>

using namespace std;

struct node
{
	long long h,wz;
};

const int maxSize=100000;
int n;
long long smax=0;
long long a[maxSize+5];
stack <node> s;

void dandiao()
{
	int i,j;
	node n1,n2;
	
	n1.h=-1;		n1.wz=0;
	s.push(n1);
	smax=0;
	for (i=1;i<=n;i++)
	{
		n1=s.top();
		if (a[i]>n1.h)	//符合单调 
		{
			n2.h=a[i];	n2.wz=i;
			s.push(n2);
		}
		else if (a[i]==n1.h)
			continue;
		else						//不符合 
		{
			while (a[i]<=n1.h)		//弹出所有比当前这数小的点 
			{
				s.pop();
				smax=max(smax,n1.h*(i-n1.wz));		//计算面积 
				j=n1.wz;
				n1=s.top();
			}
			n2.h=a[i];	n2.wz=j;	//进栈 
			s.push(n2);
		}
	}
	n1=s.top();
	while (n1.wz!=0)
	{
		smax=max(smax,n1.h*(i-n1.wz));
		s.pop();
		n1=s.top();
	}
	s.pop();
	
	printf("%lld\n",smax);
}

int main()
{
	int i;
	
	freopen("a.txt","r",stdin);
	while (1)
	{
		scanf("%d",&n);
		if (n==0)
			break;
		for (i=1;i<=n;i++)
			scanf("%d",&a[i]);
		dandiao();
	}
	
	
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值