单调栈
单调栈,顾名思义,就是使得存在栈中的数据符合某种单调性。
常见的应用模型是求数组中某元素左边/右边第1个比其大/小的数。
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 3000010;
int st[N];
int a[N];
int tt; // 定义栈首指针
vector<int> ans;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
// 从最右边元素开始找
for (int i = n; i >= 1; i--) {
while(tt && a[st[tt]] <= a[i]) tt--; // 如果栈不为空且栈顶元素小于当前值
ans.push_back(tt ? st[tt] : 0); // 记录答案
st[++tt] = i; // 元素下标入栈
}
reverse(ans.begin(), ans.end());
for (auto x : ans) cout << x << " ";
return 0;
}
单调队列
对于数组[1 3 -1 -3 5 3 6 7]
, 窗口大小为3
过程如下:
[1 3 -1] -3 5 3 6 7
1 [3 -1 -3] 5 3 6 7
1 3 [-1 -3 5] 3 6 7
1 3 -1 [-3 5 3] 6 7
1 3 -1 -3 [5 3 6] 7
1 3 -1 -3 5 [3 6 7]
那么该如何采用单调队列来维护这个滑动窗口呢?
假定求滑动窗口的最小值,可以发现,如果当前数比前面的数要小,则这个数肯定不会再被使用到,那么就可以将其出队,即队尾元素出队,这样队列元素满足某种单调性,即这是个单调队列。
另外,在每次移动窗口时,要判断队头元素是否已超出窗口,超出则让其出队。
所以,我们可以使用双端队列实现。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int hh = 0, tt = -1;
int q[N], a[N];
int n, k;
vector<int> ans;
int main()
{
cin >> n >> k;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++) {
if (hh <= tt && i - q[hh] + 1 > k) hh++; // 最左边元素已超出窗口
while (hh <= tt && a[q[tt]] >= a[i]) tt--; // 如果队尾元素大于当前元素,则队尾元素不再会被使用,出队
q[++tt] = i; // 进入队列
if (i >= k) ans.push_back(a[q[hh]]); // 记录答案
}
for (auto x : ans) cout << x << " ";
cout << endl;
ans.clear();
hh = 0, tt = -1;
// 最大值同理
for (int i = 1; i <= n; i++) {
if (hh <= tt && i - q[hh] + 1 > k) hh++;
while (hh <= tt && a[q[tt]] <= a[i]) tt--;
q[++tt] = i;
if (i >= k) ans.push_back(a[q[hh]]);
}
for (auto x : ans) cout << x << " ";
return 0;
}