zoukankan      html  css  js  c++  java
  • 洛谷P1886 滑动窗口 题解 单调队列

    题目链接:https://www.luogu.com.cn/problem/P1886

    题目大意:
    给你一个长度为 (n) 的数组 (a) 以及 (k),对于所有 (ge k)(i) ,求:区间 ([i-k+1, i]) 的最大值和最小值。

    解题思路:
    单调队列。
    对于求区间最小值,维护一个单调递增的单调队列;
    对于求区间最大值,维护一个单调递减的单调队列。

    实现代码如下:

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 1000010;
    int n, k, a[maxn];
    deque<int> que;
    int main() {
        cin >> n >> k;
        for (int i = 1; i <= n; i ++) cin >> a[i];
        for (int i = 1; i <= n; i ++) {
            while (!que.empty() && a[que.back()] >= a[i]) que.pop_back();
            que.push_back(i);
            if (que.front() < i-k+1) que.pop_front();
            if (i > k) putchar(' ');
            if (i >= k) cout << a[que.front()];
        }
        cout << endl;
        que.clear();
        for (int i = 1; i <= n; i ++) {
            while (!que.empty() && a[que.back()] <= a[i]) que.pop_back();
            que.push_back(i);
            if (que.front() < i-k+1) que.pop_front();
            if (i > k) putchar(' ');
            if (i >= k) cout << a[que.front()];
        }
        cout << endl;
        return 0;
    }
    
  • 相关阅读:
    Element节点
    Document节点
    ParentNode接口,ChildNode接口
    NodeList接口,HTMLCollection接口
    Node接口
    DOM概述
    Promise对象
    定时器
    IT常用日语
    配置JavaWeb开发环境
  • 原文地址:https://www.cnblogs.com/quanjun/p/12296576.html
Copyright © 2011-2022 走看看