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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章