zoj 3349 Special Subsequence(dp+线段树优化)

Time Limit: 5000MS Memory Limit: 32768KB 64bit IO Format: %lld & %llu

[]   [Go Back]   [Status]  

Description

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

题意:给定数列a,求一个相邻的数差小于d的子序列

题解:相信n方的dp很容易就可以想出来,dp【i】=dp【j】+1(0<=j<i&&abs(a【i】-a【j】)<=d)

           重点就是如何快速找到满足abs(a【i】-a【j】)<=d的j,这里用一棵线段树就能维护。先将a数列离散化,然后一一对应建立一棵线段树(树保存区间内所有数最长子序列的最值),然后就可以快速更新出dp【i】了,详细如代码


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#define maxn 100008
using namespace std;
int a[maxn],b[maxn],tree[maxn<<2];
void update(int pos,int left,int right,int loc,int val)
{
    int mid=(left+right)>>1;
    if(left==right){ tree[pos]=val; return; }
    if(loc<=mid) update(pos<<1,left,mid,loc,val);
    else update(pos<<1|1,mid+1,right,loc,val);
    tree[pos]=max(tree[pos<<1],tree[pos<<1|1]);
}
int query(int pos,int left,int right,int ltemp,int rtemp)
{
    int mid=(left+right)>>1,temp=0;
    if(ltemp<=left&&right<=rtemp) return tree[pos];
    if(ltemp<=mid) temp=max(temp,query(pos<<1,left,mid,ltemp,rtemp));
    if(rtemp>mid) temp=max(temp,query(pos<<1|1,mid+1,right,ltemp,rtemp));
    return temp;
}
int main()
{
    int n,d,all,res,i;

    while(scanf("%d%d",&n,&d)>0)
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",a+i);
            b[i]=a[i];
        }
        sort(a,a+n);
        all=unique(a,a+n)-a;
        memset(tree,0,sizeof(tree));
        for(res=i=0;i<n;i++)
        {
            int left=lower_bound(a,a+all,b[i]-d)-a;
            int right=upper_bound(a,a+all,b[i]+d)-a-1;
            int temp=query(1,0,all-1,left,right);
            res=max(res,temp+1);
            update(1,0,all-1,lower_bound(a,a+all,b[i])-a,temp+1);
        }
        printf("%d\n",res);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值