单调栈的进一步理解,poj2796

对于单调栈,则是一个单调的栈,为什么可以把复杂度减小为0(n);;主要是在求以一个数为最小的区间和的时候,可以在数据处理时构建一个单调栈,已知一个单调的栈,再往下面压入一个数时,如果不满足单调性,则表明暂栈顶元素最小的区间已经结束了,那么就pop出来,如果栈顶第二个元素也不满足单调性,那么也压出,但是由于栈顶第一个元素肯定在第二个的最小区间内(应为大于倒数第二个)所以要建立一个tmp,储存这个元素之前的pop出的值得和,而在pop后面的值时,则是加上tmp,也就会吧之前比他大的一起加上了;;;

所以只要对最后的栈顶元素一步一步处理就可以得到所需要的和


poj2796代码::

#include <iostream>
#include <cstdio>
using namespace std;

const int N = 100005;

struct Elem
{
	long long height;
	long long width;
	int begin;
	int count;
};

Elem stack[N];
int top;

int main()
{
	int num, n;
	long long ans, tmp, tot;
	int ansbeg, ansend, count;
	scanf("%d", &n);
	top = 0;
	ans = 0;
	ansbeg = ansend = 1;
	for (int i = 0; i < n; ++i)
	{
		scanf("%d", &num);
		tmp = 0;
		count = 0;
		while (top > 0 && stack[top - 1].width >= num)
		{
			stack[top - 1].count += count;
			tot = (stack[top - 1].height + tmp) * stack[top - 1].width;
			if (tot > ans)
			{
				ans = tot;
				ansbeg = stack[top - 1].begin;
				ansend = ansbeg + stack[top - 1].count - 1;
			}
			tmp += stack[top - 1].height;
			count = stack[top - 1].count;
			--top;
		}
		stack[top].height = num + tmp;
		stack[top].width = num;
		stack[top].begin = i + 1 - count;
		stack[top].count = 1 + count;
		++top;
	}
	tmp = 0;
	count = 0;
	while (top > 0)
	{
		stack[top - 1].count += count;
		tot = (stack[top - 1].height + tmp) * stack[top - 1].width;
		if (tot > ans)
		{
			ans = tot;
			ansbeg = stack[top - 1].begin;
			ansend = ansbeg + stack[top - 1].count - 1;
		}
		tmp += stack[top - 1].height;
		count = stack[top - 1].count;
		--top;
	}
	printf("%lld\n%d %d\n", ans, ansbeg, ansend);
	return 0;
}

代码非原创;;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值