hdu 3450 Counting Sequences 树状数组+DP 求相邻两个数字的绝对值小于等于H并且序列长度的序列个数

Problem Description
For a set of sequences of integers{a1,a2,a3,...an}, we define a sequence{ai1,ai2,ai3...aik}in which 1<=i1<i2<i3<...<ik<=n, as the sub-sequence of {a1,a2,a3,...an}. It is quite obvious that a sequence with the length n has 2^n sub-sequences. And for a sub-sequence{ai1,ai2,ai3...aik},if it matches the following qualities: k >= 2, and the neighboring 2 elements have the difference not larger than d, it will be defined as a Perfect Sub-sequence. Now given an integer sequence, calculate the number of its perfect sub-sequence.
 


 

Input
Multiple test cases The first line will contain 2 integers n, d(2<=n<=100000,1<=d=<=10000000) The second line n integers, representing the suquence
 


 

Output
The number of Perfect Sub-sequences mod 9901
 


 

Sample Input
  
  
4 2 1 3 7 5
 


 

Sample Output
  
  
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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值