洛谷-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;
}
相关推荐
无限码力12 小时前
携程0510笔试真题【单数组交换】
算法·携程笔试·携程笔试真题·携程0510笔试真题
BlockWay13 小时前
WEEX Labs 周度观察:微软-OpenAI 合作调整与AI 多云趋势
大数据·人工智能·算法·安全·microsoft
风筝在晴天搁浅13 小时前
快手 CodeTop LeetCode 224.基本计算器
数据结构·算法·leetcode
Smoothcloud润云13 小时前
5大功能精修,重构AI算力使用体验!
java·人工智能·windows·算法·重构·编辑器·sublime text
郝学胜-神的一滴14 小时前
中级OpenGL教程 008:精准控制高光光斑大小与强度
c++·unity·godot·three.js·图形学·opengl·unreal
计算机安禾14 小时前
【算法分析与设计】第41篇:确定性与非确定性多项式时间:P与NP的形式化
算法
牢姐与蒯14 小时前
c++数据结构之c++11(一)
数据结构·c++
折戟不必沉沙14 小时前
构造和析构函数能否是虚函数?能否调用虚函数?
c++
leo__52014 小时前
随机接入退避算法过程模拟实现
网络·算法
-To be number.wan15 小时前
算法日记 | STL- sort排序
c++·算法