跳到正文

个人记录

7.14

wmml约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月15日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟

版本

  1. v1当前

单调队列:是一种特殊的队列结构,主要用于维护滑动窗口内的极值(最大值或最小值),能够在 O(n) 时间内高效解决相关问题。

入队:新元素从队尾入队,移除破坏单调性的队尾元素。

出队:检查队首元素是否超出窗口范围,若超出则弹出。

T1

C++
#include<bits/stdc++.h>
using namespace std;
#define int unsigned long long 
int n,k,q[1000010],a[1000010];
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>k;
	for(int i=1;i<=n;i++)cin>>a[i];
	int l=1,r=0;
	for(int i=1;i<=n;i++){
		while(l<=r&&a[i]>=a[q[r]]){
			r--;//存下标 
		}
		q[++r]=i; 
		if(i>=k+q[l]){
			l++;
		}//弹队首 
		if(i>=k){
			cout<<r-l+1<<"\n"; 
		} 
	}
	return 0;
}

T2

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+5,inf=1e18;
int n,m;
int a[N];
int q[N];
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	} 
	int l=1,r=0;
	for(int i=1;i<=n;i++){
		while(l<=r && a[q[r]]>=a[i]){
			r--;
		}
		while(l<=r && q[l]+m<=i){
			l++;
		}
		q[++r]=i;
		if(i>=m){
			cout<<a[q[l]]<<" ";
		}
	}
	cout<<"\n";
	l=1,r=0;
	for(int i=1;i<=n;i++){
		while(l<=r && a[q[r]]<=a[i]){
			r--;
		}
		while(l<=r && q[l]+m<=i){
			l++;
		}
		q[++r]=i;
		if(i>=m){
			cout<<a[q[l]]<<" ";
		}
	}
	return 0;
}
原文