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

题目描述

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

例如,对于序列 1,3,−1,−3,5,3,6,7 以及 k=3,有如下过程:

输入格式

输入一共有两行,第一行有两个正整数 n,k;

第二行有 n 个整数,表示序列 a。

输出格式

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

第二行为每次窗口滑动的最大值。

输入输出样例

输入 #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% 的数据,1≤n≤105;

对于 100% 的数据,1≤k≤n≤106,ai​∈[−231,231)。

题解

cpp 复制代码
#include <bits/stdc++.h>
// #include<iostream>
// #include<iomanip>
// #include<vector>
// #include<queue>
// #include<cstring>
// #include <algorithm>
// #define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
using namespace std;
#define pii pair<int, int>
#define endl '\n'
const int M = 1e6 + 7;
const int N = 1e8 + 7;

int a[M],b[M];
int q[M],hh=0,tt=-1;

int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
int n,k;
cin>>n>>k;
rep(i,1,n)cin>>a[i];

rep(i,1,n)
{
  if(hh<=tt&&q[hh]<i-k+1)hh++;
  while(hh<=tt&&a[i]<=a[q[tt]])tt--;
  q[++tt]=i;
   if(i>=k)b[i]=a[q[hh]];
}
rep(i,k,n)cout<<b[i]<<' ';
cout<<endl;
hh=0,tt=-1;
rep(i,1,n)
{
  if(hh<=tt&&q[hh]<i-k+1)hh++;
  while(hh<=tt&&a[i]>=a[q[tt]])tt--;
  q[++tt]=i;
   if(i>=k)b[i]=a[q[hh]];
}
rep(i,k,n)cout<<b[i]<<' ';
cout<<endl;

      return 0;
}
相关推荐
aqiu11111139 分钟前
【C++算法打怪专栏】8. 字符串转换整数 (atoi)
开发语言·c++·算法
h39746 小时前
DirectShow过滤器开发-视频源过滤器
c++·windows·音视频·directshow
程序猿编码7 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
西飘客8 小时前
vs 怎么根据dll 生成lib文件
c++·qt
程序员老陆9 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
信奥卷王9 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵9 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG11 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z11 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode