您的位置:首页 > 产品设计 > UI/UE

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

2011-10-10 22:02 330 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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

[align=left]Output[/align]
The number of Perfect Sub-sequences mod 9901

[align=left]Sample Input[/align]

4 2
1 3 7 5


[align=left]Sample Output[/align]

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
);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐