1.830. 单调栈 - AcWing题库
模板
// 找出每个数左边离它最近的比它大/小的数
int tt = 0;
for(int i = 0; i <= n; i++){
while(tt && check(stk[tt] ,i)) tt--;
stk[++tt] = i;
}
#include<iostream>
using namespace std;
const int N = 1e5+10;
int stk[N], tt;
int main(){
int n;
cin >> n;
while(n--){
int x;
cin >> x;
while(tt && stk[tt] >= x) tt--;
if(!tt) cout << "-1" << " ";
else cout << stk[tt] << " ";
stk[++tt] = x;
}
return 0;
}
只要不满足题目中的条件的时候就弹出栈顶元素 (tt--)
保证这个栈中的一个单调性