洛谷P3512 [POI2010]PIL-Pilots 题解

洛谷P3512 [POI2010]PIL-Pilots 题解

题目链接:P3512 [POI2010]PIL-Pilots

题意:给定 n n n 个数,找一个最长区间,使得区间中的最大值减最小值不超过 k k k

题面写的太烂了

考虑用两个单调队列分别维护从 1 1 1 i i i 的最大值和最小值

注意pop()时候的判断,具体见代码

时间复杂度 O ( n ) O(n) O(n)

代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <random>
using namespace std;
// #define int long long
// #define INF 0x3f3f3f3f3f3f3f3f
#define INF 0x3f3f3f3f
namespace FastIO
{
    #define gc() readchar()
    #define pc(a) putchar(a)
    #define SIZ (int)(1e6+15)
    char buf1[SIZ],*p1,*p2;
    char readchar()
    {
        if(p1==p2)p1=buf1,p2=buf1+fread(buf1,1,SIZ,stdin);
        return p1==p2?EOF:*p1++;
    }
    template<typename T>void read(T &k)
    {
        char ch=gc();T x=0,f=1;
        while(!isdigit(ch)){if(ch=='-')f=-1;ch=gc();}
        while(isdigit(ch)){x=(x<<1)+(x<<3)+(ch^48);ch=gc();}
        k=x*f;
    }
    template<typename T>void write(T k)
    {
        if(k<0){k=-k;pc('-');}
        static T stk[66];T top=0;
        do{stk[top++]=k%10,k/=10;}while(k);
        while(top){pc(stk[--top]+'0');}
    }
}using namespace FastIO;
#define N (int)(3e6+15)

int n,k,pre,res,a[N];
int st1,en1,st2,en2,q1[N],q2[N];
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    // freopen("check.in","r",stdin);
    // freopen("check.out","w",stdout);
    read(k);read(n);
    for(int i=1; i<=n; i++) read(a[i]);
    if(n==1)return write(1),0;
    st1=st2=en1=en2=1;
    q1[++en1]=1;q2[++en2]=1; pre=1;
    for(int i=2; i<=n; i++)
    {
        while(st1<en1&&a[q1[en1]]<a[i])--en1;
        while(st2<en2&&a[q2[en2]]>a[i])--en2;
        q1[++en1]=i; q2[++en2]=i;
        while(a[q1[st1+1]]-a[q2[st2+1]]>k)
        {
            if(q1[st1+1]<q2[st2+1])
                pre=q1[st1+1]+1,++st1;
            else pre=q2[st2+1]+1,++st2;
        }
        res=max(res,i-pre+1);
    }
    write(res);
    return 0;
}

转载请说明出处

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值