ZOJ3349 Special Subsequence(dp+線段樹)

Special Subsequence

傳送門1
傳送門2
There a sequence S with n integers , and A is a special subsequence that satisfies |AiAi1|<=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


題意

給定一個序列S,求最長的子序列滿足相鄰兩個數差值不超過d.

分析

類似於LIS,有dp的轉移方程:

()dp[i]=max|a[i]a[j]|<=ddp[j]+1

但時間複雜度O(n2)
顯然超時.
於是要進行優化,顯然會想到線段樹.
可以用一個B數組存儲A去重排序後的數列,用B建樹。
然後用線段樹查找,則() 式複雜度降爲O(logn)
故此時複雜度爲O(nlogn) .

CODE

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 100005
#define FOR(i,a,b) for(int i=(a),i##_END_=(b);i<=i##_END_;i++)
#define Lson l,mid,p<<1
#define Rson mid+1,r,p<<1|1
#define Mx(a,b) if(a<(b))a=(b)
using namespace std;
int Tree[N<<2];
int A[N],B[N];
int n,d,B_n;
void rd(int &x) {
    char c;x=0;
    while((c=getchar())<48);
    do x=(x<<1)+(x<<3)+(c^48);
    while((c=getchar())>47);
}

int Query(int nl,int nr,int l,int r,int p) {
    if(nl<=l&&r<=nr) return Tree[p];
    int mid=(l+r)>>1,mx=0;
    if(nl<=mid)mx=Query(nl,nr,Lson);
    if(nr>mid)mx=max(mx,Query(nl,nr,Rson));
    return mx;
}
void Update(int pos,int v,int l,int r,int p) {
    if(l==r) {
        Mx(Tree[p],v);
        return;
    }
    int mid=(l+r)>>1;
    if(pos<=mid)Update(pos,v,Lson);
    else if(pos>mid)Update(pos,v,Rson);
    Tree[p]=max(Tree[p<<1],Tree[p<<1|1]);
}
int main() {
    while (scanf("%d",&n)!=EOF) {
        rd(d);
        FOR(i,1,n) {
            rd(A[i]);
            B[i]=A[i];
        }
        sort(B+1,B+n+1);
        int B_n=unique(B+1,B+n+1)-B-1,ans=0,x;
        memset(Tree,0,sizeof Tree);
        FOR(i,1,n) {
            x=Query(
                lower_bound(B+1,B+B_n+1,A[i]-d)-B-1,
                upper_bound(B+1,B+B_n+1,A[i]+d)-B-2,
                0,
                B_n,
                1
            );
            Update(
                lower_bound(B+1,B+B_n+1,A[i])-B-1,
                x+1,
                0,
                B_n,
                1
            );
            Mx(ans,x+1);
        }
        printf("%d\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章