有了单调队列的学习和理解自然不难理解单调栈.
维护操作:如果维护单调递增栈,若带插入元素小于栈顶元素则将栈顶元素弹出,直至栈顶元素小于当前带插入元素,将其入栈(相反操作则维护单调递减栈).
性质:维护区间最近大于关系(反之亦成立).
下面一道经典的例题,来帮助读者进一步去理解单调栈.
http://oj.haizeix.com/problem/264
解题思路:用栈来存储若干个矩形,矩形的高度是单调递增的,如果当前矩形比栈顶矩形高则入栈,否则不断取出栈顶,直至栈为空或者矩形高度比当前矩形小,出栈过程中累计矩形宽度,计算出出栈矩形的面积,然后将当前矩形入栈(宽度值为累积和加一).
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
#define SIZE 100000
ll stack[SIZE + 5];
ll arr[SIZE + 5];
int width[SIZE + 5];
int main() {
int n, top = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lld", &arr[i]);
}
arr[n + 1] = 0;
stack[top] = 0;
ll ans = 0;
for (int i = 1; i <= n + 1; i++) {
if (arr[i] > stack[top]) {
stack[++top] = arr[i];
width[top] = 1;
}
else {
int wid = 0;
while (arr[i] < stack[top]) {
wid += width[top];
ans = max(ans, (ll)wid * stack[top]);
top--;
}
stack[++top] = arr[i], width[top] = wid + 1;
}
}
printf("%lld\n", ans);
return 0;
}