题解:
线段树优化DP
令f[i]表示到 i 位置满足题意的子序列长度的最大值
转移显然 f[i]=max(f[j])+1 (abs(i-j)<=k)
所以只需要离散化后建一棵权值线段树,单点修改,区间查询最大值即可
当然你想写平衡树也可以啊
//by sdfzchy
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lson L,mid,rt<<1
#define rson mid+1,R,rt<<1|1
using namespace std;
typedef long long LL;
const int inf=(1<<30),N=200100;
int n,m;
inline int in()
{
char ch=getchar();
int f=1,tmp=0;
while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {tmp=(tmp<<1)+(tmp<<3)+(ch-'0');ch=getchar();}
return tmp*f;
}
int a[N],ha[N*4],f[N];
int ma[N*12+5];
void upd(int rt)
{
ma[rt]=max(ma[rt<<1],ma[rt<<1|1]);
}
void change(int pos,int x,int L,int R,int rt)
{
if(L==R) {ma[rt]=max(x,ma[rt]);return;}
int mid=(L+R)>>1;
if(pos<=mid) change(pos,x,lson);
else change(pos,x,rson);
upd(rt);
}
int query(int ll,int rr,int L,int R,int rt)
{
if(ll<=L&&rr>=R) return ma[rt];
int mid=(L+R)>>1,ret=0;
if(ll<=mid) ret=max(ret,query(ll,rr,lson));
if(rr>mid) ret=max(ret,query(ll,rr,rson));
return ret;
}
int d;
int l[N],r[N],ans;
int main()
{
while(~scanf("%d%d",&n,&d))
{
memset(f,0,sizeof(f));
memset(ma,0,sizeof(ma));
for(int i=1;i<=n;i++) a[i]=in(),ha[3*i-2]=a[i]-d,ha[3*i-1]=a[i],ha[3*i]=a[i]+d;
sort(ha+1,ha+3*n+1);
int len=unique(ha+1,ha+3*n+1)-ha-1;
for(int i=1;i<=n;i++)
{
l[i]=lower_bound(ha+1,ha+len+1,a[i]-d)-ha;
r[i]=lower_bound(ha+1,ha+len+1,a[i]+d)-ha;
a[i]=lower_bound(ha+1,ha+len+1,a[i])-ha;
}
for(int i=1;i<=n;i++)
{
f[i]=query(l[i],r[i],1,len,1)+1;
change(a[i],f[i],1,len,1);
ans=max(ans,f[i]);
}
printf("%d\n",ans);
ans=0;
}
return 0;
}