首先我们有一个显然的
O(n2)
dp。倒着做即可。
考虑如何优化,对于第i个点,我其实是在i+1~n中的权值>=x+d和权值<=x-d的点中选一个最大的来转移,我们可以用离散化+两个树状数组来实现查询前缀后缀最大值。复杂度
O(nlogn)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
#define N 100010
inline char gc(){
static char buf[1<<16],*S,*T;
if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
return *S++;
}
inline ll read(){
ll x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
return x*f;
}
int n,m,d,c1[N],c2[N],ans[N],to[N];
ll a[N],aa[N];
inline int Max(int x,int y){return ans[x]<ans[y]?y:x;}
inline void add1(int x,int val){
for(;x<=m;x+=x&-x) c1[x]=Max(c1[x],val);
}
inline void add2(int x,int val){
for(;x<=m;x+=x&-x) c2[x]=Max(c2[x],val);
}
inline int ask1(int x){
int res=0;for(;x;x-=x&-x) res=Max(res,c1[x]);return res;
}
inline int ask2(int x){
int res=0;for(;x;x-=x&-x) res=Max(res,c2[x]);return res;
}
int main(){
// freopen("a.in","r",stdin);
n=read();d=read();
for(int i=1;i<=n;++i) a[i]=aa[i]=read();
sort(aa+1,aa+n+1);m=unique(aa+1,aa+n+1)-aa-1;
for(int i=n;i>=1;--i){
int x=lower_bound(aa+1,aa+m+1,a[i]+d)-aa;
int y=upper_bound(aa+1,aa+m+1,a[i]-d)-aa-1;
int res=Max(ask1(y),ask2(m-x+1));
ans[i]=ans[res]+1;to[i]=res;int pos=lower_bound(aa+1,aa+m+1,a[i])-aa;
add1(pos,i);add2(m-pos+1,i);
}int res=0;for(int i=1;i<=n;++i) res=Max(res,i);
printf("%d\n",ans[res]);
while(res){printf("%d ",res);res=to[res];}
return 0;
}