【算法】【单调栈】单调栈 单调栈 单调栈

找每个数左边离它最近的比它大/小的数

模板

stack<int> st;
for(int i = 1; i <= n; i++)
{
      while(st.size() > 0 && x <= st.top()) st.pop();
      st.push(arr[i]);
}

单调栈

题目链接:https://www.acwing.com/activity/content/problem/content/867/1/

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



int main()
{
    int n;
    cin >> n;
    stack<int> st;
    for(int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        
        while(!st.empty() && st.top() >= x) st.pop();
        
        if(!st.empty()) cout << st.top() << " ";
        else cout << "-1" << " ";
        
        st.push(x);
    }
    return 0;
}