[洛谷 1886] 滑动窗口

一道经典的单调队列题目

原题传送门

单调指的是元素的规律呈现为一种单调性,递增,递减,或者自定义1576249-20190816123042323-327652433.png

队列指的是只能从队首和队尾进行操作(所以单调队列也可以用STL的deque实现),但单调队列只需要队首的弹出、队尾的插入和弹出


题目的要求是每连续k个数中的最大值和最小值,以维护最大值为例,对于任意在范围内,且在队列中的数x,y,新进队一个数z,z > x && z > y,那么z从队尾进队,x,y出队

Code:

#include <bits/stdc++.h>
const int N = 1000010;
int n, k;
int q[N], a[N];
inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch))
        f = (ch == '-') ? -1 : 1, ch = getchar();
    while (isdigit(ch))
        x = x * 10 + (ch - '0'), ch = getchar();
    return x * f;
}

void GetM(int d)
{
    std::memset(q, 0, sizeof(q));
    int head = 0, tail = 0;
    for (int i = 1; i <= n; i++)
    {
        if (d ^ 1)
            while (head <= tail && a[q[tail]] >= a[i])
                tail--;
        else
            while (head <= tail && a[q[tail]] <= a[i])
                tail--;
        q[++tail] = i;
        if (i >= k)
        {
            while (q[head] <= i - k)
                head++;
            std::cout << a[q[head]] << ' ';
        }
    }
}
int main()
{
    n = read(), k = read();
    for (int i = 1; i <= n; i++)
        a[i] = read();
    GetM(0);
    std::cout << '\n';
    GetM(1);
    return 0;
}

转载于:https://www.cnblogs.com/wyctstf/p/11363161.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值