单调栈的应用

题目:求小于当前数的左边最近的数

在这里插入图片描述

#include<iostream>
#include<algorithm>

using namespace std;

const int N = 100010;

int n;
int stk[N], tt; //tt == 0时栈为空

int main(){
    
    
    int n;
    cin >> n;
    while(n --){
    
    
        int x; 
        cin >> x;
        while(tt && stk[tt] >= x) tt --;//弹出所有大于等于当前数的值
        if(tt == 0) cout << -1 << ' ';
        else cout << stk[tt] << ' ';
        
        stk[ ++ tt] = x;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44879626/article/details/108415009