Week5 D - 滑动窗口滑动窗口

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;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值