栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

单调队列模板&滑动窗口

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单调队列模板&滑动窗口

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

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

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

//弹出
hh++

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

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

using namespace std;


template  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  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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/723490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号