zju3349 Special Subsequence

Special Subsequence

Time Limit: 5 Seconds       Memory Limit: 32768 KB

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
 
 
线段树优化 
根据最暴力的做法
f[i]= f[j] +1;    j 满足  a[i]-d<=a[j]<=a[i]+d
查找a[j]值在[ a[i]-d, a[i]+d ]之间的f[j]的最大值
即可完成优化
 
 
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

typedef long long LL;

#define N 100010

struct data
{
    LL val, idx;
};

LL a[N],c[N],q[N];
LL Maxn[N*4];
data b[N];
int n;
LL ans, d;

bool cmp(data x,data y)
{
    return (x.val<y.val );
}

void update(int o, int l,int r,int x ,LL v)
{
    if (l==x && r==x)
    {
        Maxn[o]=v;
        return;
    }
    int mid=(l+r)>>1;
    if (x<= mid )  update( o*2, l, mid , x, v);
    if (x> mid  )  update( o*2+1, mid+1,r, x, v);
    Maxn[o]=max( Maxn[o*2], Maxn[o*2+1] );
}

void query(int o, int l, int r ,int x, int y)
{
    if (x<=l&&r<=y)
    {
        ans=max( Maxn[o], ans);
        return ;
    }
    int mid=(l+r)>>1;
    if (x<= mid )  query( o*2, l, mid , x, y);
    if (y> mid  )  query( o*2+1, mid+1,r, x, y);
}


int main()
{
    while (cin>>n>>d)
    {
        memset(Maxn,0,sizeof(Maxn));
        memset(q,0,sizeof(q));
        for (int i=0; i<n; i++)
        {
            cin>>a[i];
            b[i].val=a[i];  b[i].idx=i;
        }

        sort(b,b+n,cmp);

        for (int i=0; i<n; i++)
        {
            c[i]=b[i].val;
            q[ b[i].idx ]=i;
        }
        LL tot=1;
        for (int i=0; i<n; i++)
        {
            LL l=a[i]-d, r=a[i]+d;
            int ll= lower_bound(c, c+n, l) - c;
            int rr= upper_bound(c, c+n, r) - c - 1 ;
            ans=0;
            query( 1, 0, n-1, ll, rr);
            if (ans==0)
                update(1, 0, n-1, q[i], 1);
            else
            {
                update(1, 0, n-1, q[i], ans+1);
                if (ans+1>tot)  tot=ans+1;
            }
        }
        cout<<tot<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值