单调队列模板&滑动窗口

链接: 模板题
数组模拟队列基本操作

//在队尾插入元素 队友弹出元素
int q[N],hh,tt = -1;

//插入
q[++tt] = x;

//弹出
hh++

//判空
hh <= tt ? not empty : empty

//队头 队尾
q[hh]
q[tt]
#include <bits/stdc++.h>
#define fory(i,a,b) for(int i = a; i <= b; ++i)

using namespace std;


template <typename T> inline void read(T& t) {
    int f = 0, c = getchar();
    t = 0;
    while (!isdigit(c)) f |= c == '-', c = getchar();
    while (isdigit(c)) t = t * 10 + c - 48, c = getchar();
    if (f) t = -t;
}

template <typename T> void print(T x) {
    if (x < 0) x = -x, putchar('-');
    if (x > 9) print(x / 10);
    putchar(x % 10 + 48);
}

const int N = 1e6 + 100;

int n, k;
int a[N], q[N];
int hh, tt;

inline void minn() {
    hh = 0, tt = -1;
    fory(i, 0, n - 1) {
        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) print(a[q[hh]]), putchar(' ');
    }
}
inline void maxx() {
    hh = 0, tt = -1;
    fory(i, 0, n - 1) {
        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) print(a[q[hh]]), putchar(' ');
    }
}

signed main() {
    read(n), read(k);
    fory(i, 0, n - 1) read(a[i]);

    minn();
    puts("");
    maxx();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值