4 2 1 3 7 5
4
//
显然是动态规划。dp[i]表示前i个数有多少个有效的子序列。那么 dp[i]=dp[i-1]+A。 A是前面i-1个数中,与i的差值不超过d的以该数结尾的有效的子序列的个数 的和。我们可以用另外一个数组sub[i]表示以i结尾的有效的子序列的个数。 dp与sub的不同之处是dp中的子序列不一定是以第i个数结尾的。
sub[i]= sigma sub[k] ,( abs(numk],num[i])<=d )。 由于求sub的时间复杂度为O(n^2),而n太大,因此需要离散化后用树状数组。
树状数组求和是一段连续的,而sub要求和的是位于区间[num[i]-d,num[i]+d],所以要对num排序,这样就能把
[num[i]-d,num[i]+d]放到连续的区间中。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int mod=9901;
const int maxn=110000;
int n,d;
int dp[maxn];
int num[maxn],a[maxn];
int pos(int x)//求最大的<=x的数的位置
{
a[n+1]=1<<30;
int l=1,r=n+1;
while(l<r)
{
int mid=(l+r)>>1;
if(a[mid]>x) r=mid;
else l=mid+1;
}
return l-1;
}
int c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int val)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c[i]+=val;if(c[i]>=mod) c[i]-=mod;
}
}
int getsum(int x)
{
int cnt=0;
for(int i=x;i>=1;i-=lowbit(i))
{
cnt+=c[i];if(cnt>=mod) cnt-=mod;
}
return cnt;
}
int main()
{
while(scanf("%d%d",&n,&d)==2)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
a[i]=num[i];
}
sort(a+1,a+1+n);
memset(c,0,sizeof(c));
dp[0]=0;
for(int i=1;i<=n;i++)
{
int ps=pos(num[i]);
int k1=pos(num[i]-d-1);//important -1
int k2=pos(num[i]+d);
int cnt=getsum(k2)-getsum(k1);
cnt=(cnt%mod+mod)%mod;
update(ps,cnt+1);//important cnt+1
dp[i]=(dp[i-1]+cnt)%mod;
}
printf("%d\n",dp[n]);
}
return 0;
}