[AcWing 830] 单调栈

image


点击查看代码
#include<iostream>

using namespace std;
const int N = 1e5 + 10;
int stk[N], tt = 0;
int main()
{
    int n;
    scanf("%d", &n);
    while (n --) {
        int x;
        scanf("%d", &x);
        while (tt && stk[tt] >= x)  tt --;
        if (tt)    printf("%d ", stk[tt]);
        else    printf("-1 ");
        stk[++ tt] = x;
    }
    return 0;
}

  1. 维护一个单调递增的栈,每当有一个元素 x 时,将栈中比 x 大的元素删除,留下的都是比 x 小的元素;
  2. 找出单调栈中第一个比 x 小的元素,如果存在则输出,如果不存在则输出 "-1",并把比 x 大的元素都删去
  3. tt = 0 的位置不存值,用来判断栈是否为空
posted @ 2022-04-30 16:14  wKingYu  阅读(36)  评论(0)    收藏  举报