GDUT 专题一 I - 滑动窗口 2022

题面链接:https://vjudge.net/contest/477276#problem/I
题面:在这里插入图片描述

思路:单调队列,我们可以用双指针来模拟队尾入队和队头出队的过程,也可以用STL中的deque来直接实现
另外要注意的就是队列中存的应该是数组的下标,这样在下标超出窗口时才可以直接弹出
具体参考代码实现

AC代码

#include <iostream>
#include <cstdio>
#include <deque>
using namespace std;
const int N = 1e6;
int a[N + 5];
int n, m;
deque <int> q1, q2;

int main(){
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; ++i)     scanf("%d", &a[i]);
    for(int i = 1; i <= n; ++i){    //min
        if(!q1.empty() && q1.front() < i - m + 1)   q1.pop_front();
        while(!q1.empty() && a[q1.back()] >= a[i])  q1.pop_back();
        q1.push_back(i);
        if(i >= m)  printf("%d ", a[q1.front()]);
    }
    puts("");
    for(int i = 1; i <= n; ++i){
        if(!q2.empty() && q2.front() < i - m + 1)   q2.pop_front();
        while(!q2.empty() && a[q2.back()] <= a[i])  q2.pop_back();
        q2.push_back(i);
        if(i >= m)  printf("%d ", a[q2.front()]);
    }
    puts("");
    //system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值