ZOJ 3349 Special Subsequence(线段树优化DP)

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;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值