Counting Sequences
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/65536 K (Java/Others)Total Submission(s): 2687 Accepted Submission(s): 955
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
找出有几个这样的序列>=2。
每个相邻的数差值不大于D
POINT:
都离散化好。
按顺序插入树状数组。
找出当前数x,和x-d,x+d。注意二分的时候用lower还是upper。
然后把这个范围的答案贡献全部加给当前数x 还得+1(自身)。
#include <string>
#include <string.h>
#include <iostream>
#include <map>
#include <cmath>
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long LL;
#define lt x<<1
#define rt x<<1|1
const LL maxn = 200000;
const LL mod = 9901;
LL sum[maxn];
LL a[maxn],b[maxn];
LL n;
LL cnt;
void add(LL x,LL p)
{
for(LL i=x;i<=cnt;i+=i&-i)
(sum[i]+=p)%=mod;
}
LL query(LL x)
{
LL ans = 0;
for(LL i=x;i>=1;i-=i&-i)
(ans+=sum[i])%=mod;
return ans;
}
int main()
{
LL d;
while(~scanf("%lld%lld",&n,&d)){
memset(sum,0,sizeof sum);
for(LL i=1;i<=n;i++){
scanf("%lld",&a[i]);
b[i]=a[i];
}
sort(b+1,b+1+n);
cnt = unique(b+1, b+1+n)-b-1;
LL ans = 0;
for(LL i=1;i<=n;i++){
LL l = a[i]-d;
LL now=a[i];
LL r = a[i]+d;
l=lower_bound(b+1,b+1+cnt,l)-b;
now = lower_bound(b+1,b+1+cnt,now)-b;
r=upper_bound(b+1,b+1+cnt,r)-b-1;
LL ssum = (query(r)-query(l-1)+mod)%mod;//减法注意!
ans=(ans+ssum)%mod;
add(now,ssum+1);
}
printf("%lld\n",ans);
}
return 0;
}