HELLO WORLD--一起加油(🍺|

kingwzun

园龄:3年6个月粉丝:111关注:0

基本数据结构 _ 单调栈

单调栈

作用:
给定一个序列,求序列中的每一个数左边或右边第一个比他大或比他小的数在什么地方/是谁

时间复杂度: 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 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(22)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起