说明:这里双向链表list也可以替换为双端队列deque
#include <iostream>
#include <list>
using namespace std;
const int MAXN = 1e6 + 10;
int N, K;
int nums[MAXN];
list<int> window;
int main() {
cin >> N >> K;
for (int i = 1; i <= N; ++i) {
cin >> nums[i];
}
for (int i = 1; i <= N; ++i) {
while (!window.empty() && window.front() <= i - K) window.pop_front();
while (!window.empty() && nums[window.back()] >= nums[i]) window.pop_back();
window.push_back(i);
if (i >= K) cout << nums[window.front()] << " ";
}
cout << endl;
window.clear();
for (int i = 1; i <= N; ++i) {
while (!window.empty() && window.front() <= i - K) window.pop_front();
while (!window.empty() && nums[window.back()] <= nums[i]) window.pop_back();
window.push_back(i);
if (i >= K) cout << nums[window.front()] << " ";
}
cout << endl;
}