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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章