【每日一题】滑动窗口题解

滑动窗口

https://ac.nowcoder.com/acm/problem/50528

Solution








Code

#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long LL;
const int N = 1e6 + 5;
const ll mod = 1e9 + 7;
const int DEG = 30;
const double PI = acos(-1.0);
const double eps = 1e-12;
const ll inf = 1e18;
static auto faster_iostream = []() {
    std::ios::sync_with_stdio(false);  // turn off sync
    std::cin.tie(nullptr);             // untie in/out streams
    return 0;
}();
int n, m;
int q[N], a[N];
vector<int> v;
void solve1(){
  int h = 1, t = 0; // h是队头 t是队尾
  for(int i = 1; i <= n; i++){
    while(h <= t && q[h] + m <= i) h++; // 当队首元素已超出滑动窗口 从队头出队
    while(h <= t && a[i] < a[q[t]]) t--; // 这里是a[i] < a[q[t]] 比a[i]都大的都从队尾出队;
    q[++t] = i;
    if(i >= m) cout << a[q[h]] << ' ';
  }
  cout << "\n";
}
void solve2(){ // 求最大值
  int h = 1, t = 0; // h是队头 t是队尾
  for(int i = 1; i <= n; i++){
    while(h <= t && q[h] + m <= i) h++; // 当队首元素已超出滑动窗口 从队头出队
    while(h <= t && a[i] > a[q[t]]) t--; //这里是 a[i] > a[q[t]] 比a[i]都小的都从队尾出队;
    q[++t] = i;
    if(i >= m) cout << a[q[h]] << ' ';
  }
  cout << "\n";
}
int main(){
  cin >> n >> m;
  for(int i = 1; i <= n; i++){
    cin >> a[i];
  }
  solve1(); // 求最小值
  solve2(); // 求最大值
  return 0;
}
Kurisu与牛客的每日一题 文章被收录于专栏

每日一题

全部评论
不看晕针
点赞 回复 分享
发布于 2020-03-29 19:50

相关推荐

2025-12-15 11:27
门头沟学院 Java
哇哇的菜鸡oc:所有人不要理会,就好了,后面他就知道怎么回事了,只能说有的时候市场都是被宰的人搞坏的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务