Monotonic stack
Monotonic stack
Common question type: Given a sequence, on the left side of each sequence, where is the nearest number larger or smaller than it.
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
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;
}
}
Monotonic queue
Use sliding window to find the minimum value in the sequence
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
int n;
int a[N], q[N];
int k;
int main()
{
cin >> n >> k;
for(int i = 0; i < n; i ++) cin >> a[i];
int hh = 0, tt = -1;
for(int i = 0; i < n; i ++)
{
//判断队头是否已经滑出窗口
if(hh <= tt && i - k + 1 > q[hh]) hh ++;
while(hh <= tt && a[q[tt]] >= a[i]) tt --;
q[++ tt] = i;
if(i >= k - 1) cout << a[q[hh]] << ' ';
}
cout << endl;
}