P1886 滑动窗口 /【模板】单调队列

有一个长为 nn 的序列 aa,以及一个大小为 kk 的窗口。现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最大值和最小值。

例如:

The array is [1,3,-1,-3,5,3,6,7][1,3,−1,−3,5,3,6,7], and k = 3k=3。

输入格式

输入一共有两行,第一行有两个正整数 n,kn,k。 第二行 nn 个整数,表示序列 aa

输出格式

输出共两行,第一行为每次窗口滑动的最小值
第二行为每次窗口滑动的最大值

输入输出样例

输入 #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\%50% 的数据,1 \le n \le 10^51≤n≤105;
对于 100\%100% 的数据,1\le k \le n \le 10^61≤kn≤106,a_i \in [-2^{31},2^{31})ai​∈[−231,231)。

#include<iostream>
#include<vector>
#include<queue>
#include<deque> 
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
typedef long long LL;
LL n,k;
LL a[maxn];
LL q1[maxn],q2[maxn];//里面存下标 
LL max_queue()
{
	LL h=1;LL t=0;
	for(LL i=1;i<=n;i++)
	{
		while(h<=t&&q1[h]+k<=i) h++;
		while(h<=t&&a[q1[t]]<a[i]) t--;
		q1[++t]=i;
		if(i>=k) cout<<a[q1[h]]<<' ';
	}
	cout<<endl;
}
LL min_queue()
{
	LL h=1;LL t=0;
	for(LL i=1;i<=n;i++)
	{
		while(h<=t&&q2[h]+k<=i) h++;
		while(h<=t&&a[q2[t]]>a[i]) t--;
		q2[++t]=i;
		if(i>=k) cout<<a[q2[h]]<<' ';
	}
	cout<<endl;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  cin>>n>>k;
  for(LL i=1;i<=n;i++) cin>>a[i];
  min_queue();
  max_queue();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值