基本数据结构 _ 单调栈
单调栈
作用:
给定一个序列,求序列中的每一个数左边或右边第一个比他大或比他小的数在什么地方/是谁
时间复杂度: O(n)
思想:
当该元素可以入栈的时候,栈顶元素就是它左侧第一个比它小的元素。
模板代码
#include <bits/stdc++.h> #define ins 0x3f3f3f3f using namespace std; const int N = 500500; #define pii pair<int, int> int n, a[N]; int stk[N], cnt; void solve() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } cout << -1; stk[++cnt] = a[0]; for (int i = 1; i < n; i++) { while (cnt && stk[cnt] >= a[i]) cnt--; if (!cnt) cout << " " << -1; else cout << " " << stk[cnt]; stk[++cnt] = a[i]; } cout << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); solve(); return 0; }
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/16526165.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步