Special Subsequence
傳送門1
傳送門2
There a sequence with integers , and is a special subsequence that satisfies
Now your task is to find the longest special subsequence of a certain sequence
Input
There are no more than 15 cases , process till the end-of-file
The first line of each case contains two integer and as in the description.
The second line contains exact integers , which consist the sequnece .Each integer is in the range .There is blank between each integer.
There is a blank line between two cases.
Output
For each case , print the maximum length of special subsequence you can get.
Sample Input
5 2
1 4 3 6 5
5 0
1 2 3 4 5
Sample Output
3
1
題意
給定一個序列S,求最長的子序列滿足相鄰兩個數差值不超過d.
分析
類似於LIS,有dp的轉移方程:
但時間複雜度 ,
顯然超時.
於是要進行優化,
可以用一個B數組存儲A去重排序後的數列,用B建樹。
然後用線段樹查找,則 式複雜度降爲
故此時複雜度爲 .
CODE
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#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;
}