There a sequence S with n integers , and A is a special subsequence that satisfies |Ai-Ai-1| <= d ( 0 <i<=|A|))
Now your task is to find the longest special subsequence of a certain sequence S
Input
There are no more than 15 cases , process till the end-of-file
The first line of each case contains two integer n and d ( 1<=n<=100000 , 0<=d<=100000000) as in the description.
The second line contains exact n integers , which consist the sequnece S .Each integer is in the range [0,100000000] .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
dp[i] = max{ dp[j] + 1, if |a[i] - a[j]| <= d };
线段树的每个叶子节点表示以i为结尾的最长子串长度
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #include<algorithm> #define N 400489 int a[N],b[N]; int tree[N]; void update(int pos, int v,int l,int r,int id) { if(l==r&&pos==l) { tree[id]=max(tree[id],v); return; } int mid=(l+r)/2; if(pos<=mid) update(pos,v,l,mid,id*2); else update(pos,v,mid+1,r,id*2+1); tree[id]=max(tree[id<<1],tree[id*2+1]); } int query(int ql,int qr,int l,int r,int id) { if(ql<=l&&r<=qr) return tree[id]; int mid=(l+r)/2; int ret=0; if(ql<=mid) ret=max(ret,query(ql,qr,l,mid,id*2)); if(qr>mid) ret=max(ret,query(ql,qr,mid+1,r,id*2+1)); return ret; } int main() { int n,tot,d; while(scanf("%d%d",&n,&d)==2) { for(int i=0;i<n;i++) scanf("%d",a+i),b[i]=a[i]; sort(b,b+n); memset(tree,0,sizeof tree); int tot=unique(b,b+n)-b; int ans=1; for(int i=0;i<n;i++) { int l=lower_bound(b,b+tot,a[i]-d)-b; int r=upper_bound(b,b+tot,a[i]+d)-b-1; int pos=lower_bound(b,b+tot,a[i])-b; int t= query(l,r,0,tot,1)+1; ans=max(ans,t); update(pos,t,0,tot,1); } cout<<ans<<endl; } }