单调队列

例题
唯一的思想就是

  • 注意一定要判断队列不为空时

首先要把过期的元素删掉。
最小值:如果他小于他前面的,那么前面的一定不是最优解
最大值:如果他大于前面的,那么前面的一定不是最优解

#include<bits/stdc++.h>
using namespace std;
struct dd {
	int num,x;
	dd(int xx=0,int yy=0):num(xx),x(yy) {
	}
};
const int maxn=1000000+20;
deque<dd>op;
int minn[maxn],maxx[maxn],a[maxn];
int main() {
	int m,n;
	cin>>m>>n;
	for(int i=1; i<=m; i++) {
		cin>>a[i];
	}
	//先求最小值
	//单调队列求最小值
	for(int i=1; i<=m; i++) {//
	if(!op.empty())
	{
	while(op.front().x<i-n+1) {
			op.pop_front();
			if(op.empty())break;
		}
		while(op.back().num>a[i]&&!op.empty()) {
			op.pop_back();
			if(op.empty())break;
		}
	}
		
		op.push_back(dd(a[i],i));
		if(i>=n)
		cout<<op.front().num<<" ";

	}
	cout<<endl;
	op.clear();
//	for(int i=1; i<=n-1; i++) {
     //op.push_back(dd(a[i],i));
//	}
	for(int i=1; i<=m; i++) {//单调队列求最大值 
	if(!op.empty())
	{
	while(op.front().x<i-n+1) {
			op.pop_front();
			if(op.empty())break;
		}
		while(op.back().num<a[i]&&!op.empty()) {
			op.pop_back();
			if(op.empty())break;
		}
	
	}
			op.push_back(dd(a[i],i));
		if(i>=n)
		cout<<op.front().num<<" ";

	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值