基本数据结构 _ 单调栈
单调栈
作用:
给定一个序列,求序列中的每一个数左边或右边第一个比他大或比他小的数在什么地方/是谁
时间复杂度: 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;
}

浙公网安备 33010602011771号