Counting Sequences
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/65536 K (Java/Others)Total Submission(s): 2849 Accepted Submission(s): 996
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
Source
题意:找长度大于1的且相邻两个数字的差值不超过d的子序列。
思路:这些数很大,需要离散化处理,我们可以发现以[a[i]-d,a[i]+d]为结尾的子序列,再加上a[i]也是符合题意的子序列。我没们就用线段树按照输入顺序一个个加到树里面。
代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e5+10;
const int mod=9901;
int n,d;
int sum[N<<2];
int a[N],b[N];
void update(int k,int num,int l,int r,int x)
{
if(l==r&&l==k)
{
sum[x]+=num;
sum[x]%=mod;
return;
}
int mid=(l+r)/2;
if(k<=mid)update(k,num,l,mid,x*2);
else update(k,num,mid+1,r,x*2+1);
sum[x]=(sum[x*2]+sum[x*2+1])%mod;
}
int query(int l,int r,int L,int R,int x)
{
if(l<=L&&r>=R)return sum[x];
int mid=(L+R)/2;
int ans=0;
if(l<=mid)ans+=query(l,r,L,mid,x*2);
if(r>mid)ans+=query(l,r,mid+1,R,x*2+1);
return ans%mod;
}
int main()
{
while(~scanf("%d %d",&n,&d))
{
memset(sum,0,sizeof(sum));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(b+1,b+n+1);
int cnt = unique(b+1, b+1+n)-b-1;
int ans=0;
for(int i=1;i<=n;i++)
{
int l=lower_bound(b+1,b+1+cnt,a[i]-d)-b;
int r=upper_bound(b+1,b+1+cnt,a[i]+d)-b-1;
int pos=lower_bound(b+1,b+1+cnt,a[i])-b;
int ans1=query(l,r,1,cnt,1);
ans=(ans+ans1)%mod;
update(pos,ans1+1,1,cnt,1);
}
printf("%d\n",ans);
}
return 0;
}