Week5 D - 滑动窗口滑动窗口
ZJM 有一个长度为 n 的数列和一个大小为 k 的窗口, 窗口可以在数列上来回移动. 现在 ZJM 想知道在窗口从左往右滑的时候,每次窗口内数的最大值和最小值分别是多少. 例如:
数列是 [1 3 -1 -3 5 3 6 7], 其中 k 等于 3.
Window position Minimum value Maximum value
[1 3 -1] -3 5 3 6 7 -1 3
1 [3 -1 -3] 5 3 6 7 -3 3
1 3 [-1 -3 5] 3 6 7 -3 5
1 3 -1 [-3 5 3] 6 7 -3 5
1 3 -1 -3 [5 3 6] 7 3 6
1 3 -1 -3 5 [3 6 7] 3 7
Input
输入有两行。第一行两个整数n和k分别表示数列的长度和滑动窗口的大小,1<=k<=n<=1000000。第二行有n个整数表示ZJM的数列。
Output
输出有两行。第一行输出滑动窗口在从左到右的每个位置时,滑动窗口中的最小值。第二行是最大值。
Sample Input
8 3
1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3
3 3 5 5 6 7
解题思路
利用滑动窗口(如题)
滑动窗口内利用单调栈来找出最大和最小值
本题难度
(1)用 deque 会超时 建议自行构造队列
遍历时只使用两次 for 也能降低 TL 的几率
或是取消 cin 同步 加个输入优化也行
(2)我太菜了
Code
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <algorithm>
#include <deque>
#include <utility>
using namespace std;
int n,k;
int s[1000100]={0};
int main(){ios::sync_with_stdio(false);
cin>>n>>k;
int i;
for(i=0;i<n;i++){
cin>>s[i];
}
deque <pair< int , int > > st;//value nums
for(i=0;i<n;i++){//cout<<"s"<<st.front().first<<' '<<st.front().second<<' '<<i<<' ';
while(st.size()>0&&st.back().first>s[i]){
st.pop_back();
}
st.push_back (pair<int ,int>(s[i],i));
if(i>=k-1){
while(!st.empty()&&st.back().second-st.front().second+1>k){
st.pop_front();
}
cout<<st.front().first;
if(i+1!=n)cout<<' ';
else cout<<endl;
}
}
st.clear();
for(i=0;i<n;i++){//cout<<"s"<<st.front().first<<' '<<st.front().second<<' '<<i<<' ';
while(st.size()>0&&st.back().first<s[i]){
st.pop_back();
}
st.push_back (pair<int ,int>(s[i],i));
if(i>=k-1){
while(!st.empty()&&st.back().second-st.front().second+1>k){
st.pop_front();
}
cout<<st.front().first;
if(i+1!=n)cout<<' ';
else cout<<endl;
}
}
return 0;
}