洛谷P3512 [POI2010]PIL-Pilots 题解
题目链接:P3512 [POI2010]PIL-Pilots
题意:给定 $n$ 个数,找一个最长区间,使得区间中的最大值减最小值不超过 $k$
题面写的太烂了
考虑用两个单调队列分别维护从 $1$ 到 $i$ 的最大值和最小值
注意pop()
时候的判断,具体见代码
时间复杂度 $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;
}