单调队列【模板】

简介: 笔记

单调队列


传送门


模板题,背过即可


题目

1.png

输入格式

输入包含两行。


第一行包含两个整数 n 和 k,分别代表数组长度和滑动窗口的长度。


第二行有 n 个整数,代表数组的具体数值。


同行数据之间用空格隔开。


输出格式

输出包含两个。


第一行输出,从左至右,每个位置滑动窗口中的最小值。


第二行输出,从左至右,每个位置滑动窗口中的最大值。


样例


输入#1


8 3

1 3 -1 -3 5 3 6 7


输出#1


-1 -3 -3 -3 3 3

3 3 5 5 6 7


数据范围


1 ≤ N ≤ 105

1 ≤ a [ i ] ≤ 109

实现代码

数组模拟, q [ ] 存 下 标

#include <iostream>
#include <queue>
using namespace std;
const int N = 1000010;
int n, k, a[N];
int q[N], hh, tt = -1;
int main()
{
    cin >> n >> k;
    for (int i = 0; i < n; i++) cin >> a[i];
    for (int i = 0; i < n; i++) {
        while(hh <= tt && i - k + 1 > q[hh]) hh++;
        while(hh <= tt && a[q[tt]] >= a[i]) tt--;
        q[++tt] = i;
        if(i + 1 >= k) cout << a[q[hh]] << ' ';
    }
    cout << endl;
    hh = 0, tt = -1;
    for (int i = 0; i < n; i++) {
        while(hh <= tt && i - k + 1 > q[hh]) hh++;
        while(hh <= tt && a[q[tt]] <= a[i]) tt--;
        q[++tt] = i;
        if(i + 1 >= k) cout << a[q[hh]] << ' ';
    }
    return 0;
}
  • deque
#include <iostream>
#include <queue>
using namespace std;
const int N = 1000010;
deque<int> q;
int n, k, a[N];
int main()
{
    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= n; i++) {
        while(!q.empty() && i - q.front() + 1 > k) q.pop_front();
        while(!q.empty() && a[q.back()] >= a[i]) q.pop_back();
        q.push_back(i);
        if(i >= k) cout << a[q.front()] << ' ';
    }
    cout << endl;
    q = deque<int>();
    for (int i = 1; i <= n; i++) {
        while(!q.empty() && i - q.front() + 1 > k) q.pop_front();
        while(!q.empty() && a[q.back()] <= a[i]) q.pop_back();
        q.push_back(i);
        if(i >= k) cout << a[q.front()] << ' ';
    }
    return 0;
}
相关文章
|
机器学习/深度学习
【模板】优先队列
优先队列的实现形式之——大根堆 #include #include #include #include #include using namespace std; struct data{ int pq[100010]; int size=0; boo...
1076 0
|
存储 算法 C++
单调栈模板总结及应用
单调栈模板总结及应用
103 0
二分搜索的三种模板
二分搜索的三种模板
74 0
|
9月前
线段树模板
线段树模板
57 0
|
存储 算法
线段树模板与练习
线段树模板与练习
113 0
|
9月前
树状数组模板
树状数组模板
48 0
|
算法
树状数组模板与练习
树状数组模板与练习
108 0

热门文章

最新文章