当前位置: 首页 > article >正文

滑动窗口——优先队列写法

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

思路:

记录两个元素分别是元素值元素下标

因为元素下标不会过期, 所以可以用STL优先队列(priority_queue)。

分为一个升序的优先队列,降序的优先队列,每次看队首如果过期了就删掉,否则答案就是队首。

优先队列传送门

【原创】优先队列 priority_queue 详解-CSDN博客

代码:

#include <bits/stdc++.h>
using namespace std;
struct Windows{
    int x, id;
    bool operator < (const Windows &T) const { return x < T.x; }
    bool operator > (const Windows &T) const { return x > T.x; }
};
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int n, k;
    cin >> n >> k;
    priority_queue<Windows> Q; // 最大
    priority_queue<Windows, vector<Windows>, greater<Windows>> Qless; // 最小
    vector<Windows> A(n);
    for (int i = 0; i < n; i++) cin >> A[i].x, A[i].id = i;
    for (int i = 0; i < n; i++) {
        Qless.push(A[i]);
        while(Qless.top().id <= i - k) Qless.pop(); // 过期
        if (i >= k - 1) cout << Qless.top().x << ' ';  
    }
    cout << '\n';
    for (int i = 0; i < n; i++) {
        Q.push(A[i]);
        while(Q.top().id <= i - k) Q.pop(); // 过期 
        if (i >= k - 1) cout << Q.top().x << ' ';
    }
    return 0;
}


http://www.kler.cn/a/549129.html

相关文章:

  • 本地通过隧道连接服务器的mysql
  • 面试题整理:操作系统
  • 洛谷 P2894 USACO08FEB Hotel 题解
  • FFmpeg源码:url_find_protocol函数分析
  • Python Cookbook-1.13 访问子字符串
  • unity学习41:动画里的曲线curve参数 和 事件 events
  • ElementUI 的组件 Switch(开关)如何让文字显示在按钮上
  • Rust编程语言入门教程(一)安装Rust
  • 【云安全】云原生- K8S Kubelet 未授权访问
  • HTTP 与 HTTPS:协议详解与对比
  • Qt5开发入门指南:从零开始掌握跨平台开发
  • 图论(四):图的中心性——度中心性介数中心性紧密中心性
  • Redis 03章——10大数据类型概述
  • Flutter Gradle 命令式插件正式移除,你迁移旧版 Gradle 配置了吗?
  • 基于deepseek api和openweather 天气API实现Function Calling技术讲解
  • Kafka日志数据深度解析:从基础查看到高级操作全攻略
  • Testin云测(兼容性测试)
  • WeMos D1+PIR+Android 的小场景制作
  • Ubuntu 22.04 Desktop企业级基础配置操作指南
  • 「软件设计模式」适配器模式(Adapter)