单调栈

给定一个长度为 n 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。

#include <iostream>
#include <stack>
using namespace std;
int n;
stack <int> st;

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

  

posted @ 2022-11-30 22:01  !&&||  阅读(22)  评论(0)    收藏  举报