对于单调栈,则是一个单调的栈,为什么可以把复杂度减小为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;
}
代码非原创;;