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

HDU - 3450 - Counting Sequences (线段树|树状数组 + 离散化)

2018-01-23 17:07 357 查看


Counting Sequences

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/65536 K (Java/Others)

Total Submission(s): 2680    Accepted Submission(s): 952


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

2010 ACM-ICPC Multi-University Training
Contest(2)——Host by BUPT 

 

题意:

有一个由n个数构成的序列,求其中有几个完美子序列。

完美子序列要满足相邻两元素之差不大于d,且序列中元素不少于两个

思路:

遍历序列中的每一个元素,求出以该元素为末尾元素的完美子序列个数。

假设该元素值为k,则以该元素为末尾元素的完美子序列个数 = 该元素前值在[k-d,k+d]区间内的元素个数 + 以这些元素为末尾元素的完美子序列个数

然后前面的个数已经求过了,就可以直接用,用区间求和,然后更新就行了,就是用线段树或树状数组

因为d比较大,然后元素大小也没有说明,所以就用离散化处理一下

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define LL long long
#define lx x<<1
#define rx x<<1|1
#define mid ((L+R)>>1)
const int mod = 9901;
const int N = 1e5 + 10;
int n,d,sum[N<<2],I,ANS;
LL a
,Rank
;
void setRank(){
sort(Rank+1,Rank+1+n);
I = 1;
for(int i=2;i<=n;i++) if(Rank[i]!=Rank[i-1]) Rank[++I] = Rank[i];
}
int Sum(int x,int l,int r,int L,int R){
if(l<=L&&R<=r) {
return sum[x];
}
int ans = 0;
if(mid>=l) ans = Sum(lx, l, r, L, mid) % mod;
if(mid<r) ans = (ans + Sum(rx, l, r, mid+1, R)) % mod;
return ans;
}
void update(int x,LL pos,int L,int R){
if(L==R) {
int l = lower_bound(Rank+1, Rank+1+I, Rank[pos]-d) - Rank;
int r = upper_bound(Rank+1, Rank+1+I, Rank[pos]+d) - Rank - 1;
int ad = Sum(1, l, r, 1, I);
ANS = (ANS + ad) % mod;
sum[x] = (sum[x] + ad + 1) % mod;
return;
}
if(pos<=mid) update(lx, pos, L, mid);
else update(rx, pos, mid+1, R);
sum[x] = (sum[lx] + sum[rx]) % mod;
}
int main()
{
while(scanf("%d%d",&n,&d)!=EOF){
memset(sum,0,sizeof sum);
for(int i=1;i<=n;i++){
scanf("%lld",&a[i]);
Rank[i] = a[i];
}
setRank();
ANS = 0;
for(int i=1;i<=n;i++){
int pos = lower_bound(Rank+1, Rank+1+I, a[i]) - Rank;
update(1, pos, 1, I);
}
printf("%d\n",ANS);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: