NOIP题,两个单调队列即可~~~~
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int Maxn=3000005; int qx[Maxn],qd[Maxn],a[Maxn]; int lx,ld,rx,rd,n,i,j,k,ans; int read(){ int ret=0; char ch=getchar(); while (ch<'0' || ch>'9') ch=getchar(); while (ch>='0' && ch<='9') {ret=ret*10+ch-'0'; ch=getchar();} return ret; } void work(){ ans=0; for (i=j=1;j<=n;j++){ if (qd[ld]<j) ld++; if (qx[lx]<j) lx++; for (;i<=n;i++){ if (ld<=rd && lx<=rx && min(a[qx[lx]],a[i])<max(a[qd[ld]],a[i])-k) break; while (ld<=rd && a[qd[rd]]<=a[i]) rd--; qd[++rd]=i; while (lx<=rx && a[qx[rx]]>=a[i]) rx--; qx[++rx]=i; } ans=max(ans,i-j); } } int main(){ freopen("pil.in","r",stdin); freopen("pil.out","w",stdout); //scanf("%d%d",&k,&n); k=read(); n=read(); for (i=1;i<=n;i++) a[i]=read(); //scanf("%d\n",&a[i]); work(); printf("%d\n",ans); return 0; }