P1886 滑动窗口 /【模板】单调队列 寒假集训

有一个长为 nn 的序列 aa,以及一个大小为 kk 的窗口。现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最大值和最小值。

例如:

The array is [1,3,-1,-3,5,3,6,7][1,3,−1,−3,5,3,6,7], and k = 3k=3。
在这里插入图片描述

输入格式
输入一共有两行,第一行有两个正整数 n,kn,k。 第二行 nn 个整数,表示序列 aa

输出格式
输出共两行,第一行为每次窗口滑动的最小值
第二行为每次窗口滑动的最大值

输入输出样例
输入 #1复制
8 3
1 3 -1 -3 5 3 6 7
输出 #1复制
-1 -3 -3 -3 3 3
3 3 5 5 6 7
说明/提示
【数据范围】
用双端队列来下维护单调队列,实现队首为区间的最大值或者最小值

#include<bits/stdc++.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#define ls (p<<1)
#define rs (p<<1|1)

using namespace std;
const int maxn=1e6;
int a[maxn],b[maxn],id[maxn];
struct node{
    int val,id;
};
void solve(){
    int n,m;
    cin>>n>>m;
    node st[maxn];
    for(int i=1;i<=n;i++){
        cin>>st[i].val;
        st[i].id=i;
    }
    deque<node>de1;
    deque<node>de2;
    int cnt=0;
    for(int i=1;i<=n;i++){
        while(!de1.empty()&&st[i].val>=de1.back().val){//维护最大值
            de1.pop_back();
        }
        while(!de2.empty()&&st[i].val<=de2.back().val){
            de2.pop_back();
        }
        de1.push_back(st[i]);
        de2.push_back(st[i]);
        while(i-m>=de1.front().id)
            de1.pop_front();
        while(i-m>=de2.front().id)
            de2.pop_front();
        
        if(i>=m){
            a[++cnt]=de1.front().val;
            b[cnt]=de2.front().val;
        }
    }
    for(int i=1;i<=cnt;i++)
        cout<<b[i]<<" ";
    cout<<endl;
    for(int i=1;i<=cnt;i++)
        cout<<a[i]<<" ";
    cout<<endl;
}
int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值