zoukankan      html  css  js  c++  java
  • 单调栈

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

    输入格式
    第一行包含整数N,表示数列长度。

    第二行包含N个整数,表示整数数列。

    输出格式
    共一行,包含N个整数,其中第i个数表示第i个数的左边第一个比它小的数,如果不存在则输出-1。

    数据范围
    1 ≤ N ≤ 10^5
    1 ≤ 数列中元素 ≤ 10^9
    输入样例:
    5
    3 4 2 7 5
    输出样例:
    -1 3 -1 2 2

    构造单调栈

    #include <iostream>
    
    using namespace std;
    
    const int N = 100010;
    
    int n;
    int stk[N], tt;
    
    int main()
    {
        cin >> n;
    
        for(int i = 0; i < n; i++)
        {
            int x;
            cin >> x;
            while(tt && stk[tt] >= x) tt--;
            if(tt) cout << stk[tt] << " ";
            else cout << -1 << " ";
    
            stk[++tt] = x;
        }
    
        system("pause");
        return 0;
    }
    
    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    stack<int> st;
    int n;
    
    int main()
    {
        cin >> n;
        while(n--)
        {
            int x;
            cin >> x;
            while(!st.empty() && st.top() >= x) st.pop();
            if(!st.empty()) cout << st.top() << " ";
            else cout << -1 << " ";
    
            st.push(x);
        }
        
        system("pause");
        return 0;
    }
    
  • 相关阅读:
    LVM 扩容硬盘笔记
    jupyter notebook 远程访问
    samba 配置文件详解
    linux 网络挂载 windows 共享文件夹
    cmder 与 win10 wsl ( 当前目录打开wsl)
    vscode for latex
    Python 使用代理
    Python Signal(信号) 异步系统事件
    centos7 install magento
    lua笔记
  • 原文地址:https://www.cnblogs.com/ZhengLijie/p/13412011.html
Copyright © 2011-2022 走看看