传送门1
传送门2
There a sequence S S with n n integers , and A A is a special subsequence that satisfies |Ai−Ai−1|<=d(0<i<=|A|)) | A i − A i − 1 | <= d ( 0 < i <= | A | ) )
Now your task is to find the longest special subsequence of a certain sequence S S
There are no more than 15 cases , process till the end-of-file
The first line of each case contains two integer n n and d d (1<=n<=100000,0<=d<=100000000) ( 1 <= n <= 100000 , 0 <= d <= 100000000 ) as in the description.
The second line contains exact n n integers , which consist the sequnece S S .Each integer is in the range [0,100000000] [ 0 , 100000000 ] .There is blank between each integer.
There is a blank line between two cases.
For each case , print the maximum length of special subsequence you can get.
5 2
1 4 3 6 5
5 0
1 2 3 4 5
3
1
给定一个序列S,求最长的子序列满足相邻两个数差值不超过d.
类似于LIS,有dp的转移方程:
#include
#include
#include
#include
#define N 100005
#define FOR(i,a,b) for(int i=(a),i##_END_=(b);i<=i##_END_;i++)
#define Lson l,mid,p<<1
#define Rson mid+1,r,p<<1|1
#define Mx(a,b) if(a<(b))a=(b)
using namespace std;
int Tree[N<<2];
int A[N],B[N];
int n,d,B_n;
void rd(int &x) {
char c;x=0;
while((c=getchar())<48);
do x=(x<<1)+(x<<3)+(c^48);
while((c=getchar())>47);
}
int Query(int nl,int nr,int l,int r,int p) {
if(nl<=l&&r<=nr) return Tree[p];
int mid=(l+r)>>1,mx=0;
if(nl<=mid)mx=Query(nl,nr,Lson);
if(nr>mid)mx=max(mx,Query(nl,nr,Rson));
return mx;
}
void Update(int pos,int v,int l,int r,int p) {
if(l==r) {
Mx(Tree[p],v);
return;
}
int mid=(l+r)>>1;
if(pos<=mid)Update(pos,v,Lson);
else if(pos>mid)Update(pos,v,Rson);
Tree[p]=max(Tree[p<<1],Tree[p<<1|1]);
}
int main() {
while (scanf("%d",&n)!=EOF) {
rd(d);
FOR(i,1,n) {
rd(A[i]);
B[i]=A[i];
}
sort(B+1,B+n+1);
int B_n=unique(B+1,B+n+1)-B-1,ans=0,x;
memset(Tree,0,sizeof Tree);
FOR(i,1,n) {
x=Query(
lower_bound(B+1,B+B_n+1,A[i]-d)-B-1,
upper_bound(B+1,B+B_n+1,A[i]+d)-B-2,
0,
B_n,
1
);
Update(
lower_bound(B+1,B+B_n+1,A[i])-B-1,
x+1,
0,
B_n,
1
);
Mx(ans,x+1);
}
printf("%d\n",ans);
}
return 0;
}