1. 程式人生 > >洛谷P3512 [POI2010]PIL-Pilots(BZOJ2096)

洛谷P3512 [POI2010]PIL-Pilots(BZOJ2096)

單調佇列

划水

用兩個指標推,單調佇列維護最大最小值。

程式碼:

#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 3000005
#define F inline
using namespace std;
int n,k,ans,a[N],mn[N],mx[N];
F char readc(){
	static char buf[100000],*l=buf,*r=buf;
	if (l==r) r=(l=buf)+fread(buf,1,100000,stdin
); return l==r?EOF:*l++; } F int _read(){ int x=0; char ch=readc(); while (!isdigit(ch)) ch=readc(); while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc(); return x; } int main(){ k=_read(),n=_read(); for (int i=1;i<=n;i++) a[i]=_read(); int ln=1,rn=0,lx=1,rx=0,l=1,r=0; while (r<
n){ int x=a[++r]; while (ln<=rn&&a[mn[rn]]>=x) rn--; while (lx<=rx&&a[mx[rx]]<=x) rx--; mn[++rn]=mx[++rx]=r; while (a[mx[lx]]-a[mn[ln]]>k&&ln<=rn&&lx<=rx){ l++; if (mn[ln]<l) ln++; if (mx[lx]<l) lx++; } ans=max(ans,r-l+1); }
return printf("%d\n",ans),0; }