【算法】【單調棧】單調棧

單調棧

找每個數左邊離它最近的比它大/小的數

模板

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章