单调栈、单调对列

1.单调栈的应用模板

给定一个长度为N的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出-1。

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+10;
int stk[N],tt;

int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int x;
        cin>>x;
        while(tt && stk[tt]>=x) //核心逻辑语句
            tt--;
        if(!tt)
            printf("-1 ");
        else
            printf("%d ",stk[tt]);
        stk[++tt]=x;
    }
    
    return 0;
}

2.单调对列应用模板:滑动窗口

给定一个大小为n≤106
的数组。

有一个大小为k的滑动窗口,它从数组的最左边移动到最右边。

您只能在窗口中看到k个数字。

每次滑动窗口向右移动一个位置。

以下是一个例子:

该数组为[1 3 -1 -3 5 3 6 7],k为3。

窗口位置 最小值 最大值
[1 3 -1] -3 5 3 6 7 -1 3
1 [3 -1 -3] 5 3 6 7 -3 3
1 3 [-1 -3 5] 3 6 7 -3 5
1 3 -1 [-3 5 3] 6 7 -3 5
1 3 -1 -3 [5 3 6] 7 3 6
1 3 -1 -3 5 [3 6 7] 3 7
您的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6+10;
int a[N],q[N];

int main()
{
    int n,k;
    cin>>n>>k;
    for(int i=0;i<n;i++)
        cin>>a[i];
        
    int hh=0,tt=0;
    for(int i=0;i<n;i++)
    {
        //i - k + 1是以i为右端点、长度为k的区间的左端点,
        //如果q[hh]的值比左端点小,那就说明队头节点已经不在区间中了,需要弹出。
        if(hh <= tt && i-k+1>q[hh])
            hh++;
            
        while(hh <= tt && a[q[tt]]>=a[i])
            tt--;
        q[++tt]=i;
        
        if(i>=k-1)
            printf("%d ",a[q[hh]]);
    }
    
    puts("");
    
    hh=0,tt=0;
    for(int i=0;i<n;i++)
    {
        if(hh <= tt && i-k+1>q[hh])
            hh++;
            
        while(hh <= tt && a[q[tt]]<=a[i])
            tt--;
        q[++tt]=i;
        
        if(i>=k-1)
            printf("%d ",a[q[hh]]);
    }
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值