题目大意:
题解:
用两个双向队列\(deque\)模拟单调队列来维护区间,一个单调递增,一个单调递减,使当前区间的最大最小值分别出现在两个队列的队首。
#include <cstdio>
#include <deque>
#include <iostream>
using namespace std;
int n, k, a[1000010];
int main() {
deque<int> maxn, minn;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
for (int i = 0; i < k; ++i) { // 单调队列
while (!minn.empty() && a[i] < minn.back()) {
minn.pop_back();
}
minn.push_back(a[i]);
while (!maxn.empty() && a[i] > maxn.back()) {
maxn.pop_back();
}
maxn.push_back(a[i]);
}
// 窗口移动求最小
for (int i = k; i < n; ++i) {
cout << minn.front() << " ";
if (minn.front() == a[i - k]) {
minn.pop_front();
}
while (!minn.empty() && a[i] < minn.back()) {
minn.pop_back();
}
minn.push_back(a[i]);
}
cout << minn.front() << " ";
cout << endl;
// 窗口移动求最大
for (int i = k; i < n; ++i) {
cout << maxn.front() << " ";
if (maxn.front() == a[i - k]) {
maxn.pop_front();
}
while (!maxn.empty() && a[i] > maxn.back()) {
maxn.pop_back();
}
maxn.push_back(a[i]);
}
cout << maxn.front() << " ";
cout << endl;
return 0;
}