洛谷-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;
}
相关推荐
To_OC8 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵11 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC13 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
郝学胜_神的一滴19 小时前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
To_OC1 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin2 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法