单调栈与单调队列

单调栈


单调栈,顾名思义,就是使得存在栈中的数据符合某种单调性。

常见的应用模型是求数组中某元素左边/右边第1个比其大/小的数。

代码:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
const int N = 3000010;

int st[N];
int a[N];
int tt; // 定义栈首指针

vector<int> ans;

int main()
{
    int n;
    cin >> n;
    
    for (int i = 1; i <= n; i++) cin >> a[i];
    
    // 从最右边元素开始找
    for (int i = n; i >= 1; i--) {
        while(tt && a[st[tt]] <= a[i]) tt--; // 如果栈不为空且栈顶元素小于当前值
        ans.push_back(tt ? st[tt] : 0); // 记录答案 
        st[++tt] = i; // 元素下标入栈
    }
    
    reverse(ans.begin(), ans.end());
    for (auto x : ans) cout << x << " ";
    
    return 0;
}

 

单调队列


单调队列常用来处理滑动窗口问题

对于数组[1 3 -1 -3 5 3 6 7], 窗口大小为3

过程如下:
[1 3 -1] -3 5 3 6 7
1 [3 -1 -3] 5 3 6 7
1 3 [-1 -3 5] 3 6 7
1 3 -1 [-3 5 3] 6 7
1 3 -1 -3 [5 3 6] 7
1 3 -1 -3 5 [3 6 7]

那么该如何采用单调队列来维护这个滑动窗口呢?

假定求滑动窗口的最小值,可以发现,如果当前数比前面的数要小,则这个数肯定不会再被使用到,那么就可以将其出队,即队尾元素出队,这样队列元素满足某种单调性,即这是个单调队列。

另外,在每次移动窗口时,要判断队头元素是否已超出窗口,超出则让其出队。

所以,我们可以使用双端队列实现。
在这里插入图片描述

 
代码:

#include <bits/stdc++.h>

using namespace std;
const int N = 1e6 + 10;

int hh = 0, tt = -1;
int q[N], a[N];
int n, k;

vector<int> ans;

int main()
{
    cin >> n >> k;

    for (int i = 1; i <= n; i++)
        cin >> a[i];
    
    
    for (int i = 1; i <= n; i++) {
       if (hh <= tt && i - q[hh] + 1 > k) hh++; // 最左边元素已超出窗口
       while (hh <= tt && a[q[tt]] >= a[i]) tt--; // 如果队尾元素大于当前元素,则队尾元素不再会被使用,出队
       q[++tt] = i; // 进入队列
       if (i >= k) ans.push_back(a[q[hh]]); // 记录答案
    }
    
    for (auto x : ans) cout << x << " ";
    cout << endl;
    
    ans.clear();
    hh = 0, tt = -1;
    
    // 最大值同理
    for (int i = 1; i <= n; i++) {
       if (hh <= tt && i - q[hh] + 1 > k) hh++; 
       while (hh <= tt && a[q[tt]] <= a[i]) tt--;
       q[++tt] = i; 
       if (i >= k) ans.push_back(a[q[hh]]); 
    }
    
    for (auto x : ans) cout << x << " ";

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值