单调栈 模板

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

#include <bits/stdc++.h>
using namespace std;

stack<int> stk;

int main() {
   
#ifndef ONLINE_JUDGE
    freopen("D:/VS CODE/C++/in.txt", "r", stdin);
    freopen("D:/VS CODE/C++/out.txt", "w", stdout);
#endif
    int n;
    cin >> n;
    
    bool flag = false;
    while (n--) {
   
        //维护一个单调递增的单调栈
        int num;
        scanf("%d", &num);
        while (stk.size() and stk.top() >= num) {
   
            stk.pop();
        }
        if (stk.empty())
            printf("-1 ");
        else 
            printf("%d ",stk.top());
        stk.push(num);
    }

    fclose(stdin);
    fclose(stdout);
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务