题目描述
有一个长为 n 的序列 a,以及一个大小为 k 的窗口。现在这个窗口从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最小值和最大值。
例如,对于序列 [1,3,−1,−3,5,3,6,7] 以及 k=3,有如下过程:

输入格式
输入一共有两行,第一行有两个正整数 n,k;
第二行有 n 个整数,表示序列 a。
输出格式
输出共两行,第一行为每次窗口滑动的最小值;
第二行为每次窗口滑动的最大值。
输入输出样例
输入 #1
8 3 1 3 -1 -3 5 3 6 7
输出 #1
-1 -3 -3 -3 3 3 3 3 5 5 6 7
说明/提示
【数据范围】
对于 50% 的数据,1≤n≤105;
对于 100% 的数据,1≤k≤n≤106,ai∈[−231,231)。
题解
cpp
#include <bits/stdc++.h>
// #include<iostream>
// #include<iomanip>
// #include<vector>
// #include<queue>
// #include<cstring>
// #include <algorithm>
// #define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
using namespace std;
#define pii pair<int, int>
#define endl '\n'
const int M = 1e6 + 7;
const int N = 1e8 + 7;
int a[M],b[M];
int q[M],hh=0,tt=-1;
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n,k;
cin>>n>>k;
rep(i,1,n)cin>>a[i];
rep(i,1,n)
{
if(hh<=tt&&q[hh]<i-k+1)hh++;
while(hh<=tt&&a[i]<=a[q[tt]])tt--;
q[++tt]=i;
if(i>=k)b[i]=a[q[hh]];
}
rep(i,k,n)cout<<b[i]<<' ';
cout<<endl;
hh=0,tt=-1;
rep(i,1,n)
{
if(hh<=tt&&q[hh]<i-k+1)hh++;
while(hh<=tt&&a[i]>=a[q[tt]])tt--;
q[++tt]=i;
if(i>=k)b[i]=a[q[hh]];
}
rep(i,k,n)cout<<b[i]<<' ';
cout<<endl;
return 0;
}