洛谷1886-单调队列

题目链接

维护单调队列。
递增队列
递减队列

#include<iostream>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<string>
#define MAXN 1000005
using namespace std;
typedef long long ll;

int p[MAXN], q[MAXN], a[MAXN], head, tail, n, k;
//q[]存放当前入队元素在原序列中的位置:
//因为要判断是不是在k个中。

//进队列:队列中保存(递增/减序列)最小与当前的值;记录原元素所在序列位置

void maxseq(){
    head = 1; tail = 0;
    for(int i = 1; i <= n; i++){
        while(head <= tail && p[tail] <= a[i]){
            tail--;
        }
        p[++tail] = a[i];
        q[tail] = i;
        while(head <= tail && q[head] <= i-k)
            head++;
        if(i>=k) printf("%d ", p[head]);

    }
    printf("\n");

    return ;
}

void minseq(){
    head = 1; tail = 0;
    for(int i = 1; i <= n; i++){
        while(head <= tail && p[tail] >= a[i]){
            --tail;
        }
        p[++tail] = a[i];
        q[tail] = i;
        while(head <= tail && q[head] <= i-k)
            head++;
        if(i>=k) printf("%d ", p[head]);

    }
    printf("\n");

    return ;
}

int main(){
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
    }
    minseq();
    maxseq();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值