AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 830. 单调栈    原题链接    简单

作者: 作者的头像   Eternity. ,  2025-06-06 13:47:55 · 北京 ,  所有人可见 ,  阅读 2


0


  • 本质:每次查询前,把大于等于自己的元素(也就是不符合题意的元素)弹出。然后此时的栈顶元素,就是比自己小的第一个元素
  • Tips:不一定非得按照课程中讲解的模拟思路写,STL也很好用。
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

int n;
stack<int> q;

void pop(int v)
{
    while (!q.empty() && v <= q.top())
    {
        q.pop();
    }
}

int query(int v)
{
    return q.empty() ? -1 : q.top();
}

int main()
{
    // freopen("1.in", "r", stdin);
    // freopen("1.out", "w", stdout); // 把标准输出绑定到 1.out
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        pop(x); // check是否清除前面比自己大的:因为当前元素可以代表比自己大的元素。[比自己大,那么自己一定符合题意]
        cout << query(x) << ' ';
        q.push(x);
    }
    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息