【ZOJ3349】Special Subsequence

題解:
線段樹優化DP
令f[i]表示到 i 位置滿足題意的子序列長度的最大值
轉移顯然 f[i]=max(f[j])+1 (abs(i-j)<=k)
所以只需要離散化後建一棵權值線段樹,單點修改,區間查詢最大值即可
當然你想寫平衡樹也可以啊

//by sdfzchy
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lson L,mid,rt<<1
#define rson mid+1,R,rt<<1|1
using namespace std;
typedef long long LL;
const int inf=(1<<30),N=200100;
int n,m;
inline int in()
{
    char ch=getchar();
    int f=1,tmp=0;
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') {tmp=(tmp<<1)+(tmp<<3)+(ch-'0');ch=getchar();}
    return tmp*f;
}
int a[N],ha[N*4],f[N];
int ma[N*12+5];

void upd(int rt)
{
    ma[rt]=max(ma[rt<<1],ma[rt<<1|1]);
}

void change(int pos,int x,int L,int R,int rt)
{
    if(L==R) {ma[rt]=max(x,ma[rt]);return;}
    int mid=(L+R)>>1;
    if(pos<=mid) change(pos,x,lson);
    else change(pos,x,rson);
    upd(rt);
}

int query(int ll,int rr,int L,int R,int rt)
{
    if(ll<=L&&rr>=R) return ma[rt];
    int mid=(L+R)>>1,ret=0;
    if(ll<=mid) ret=max(ret,query(ll,rr,lson));
    if(rr>mid)  ret=max(ret,query(ll,rr,rson));
    return ret;
}
int d;
int l[N],r[N],ans;
int main()
{
    while(~scanf("%d%d",&n,&d))
    {
        memset(f,0,sizeof(f));
        memset(ma,0,sizeof(ma));
        for(int i=1;i<=n;i++) a[i]=in(),ha[3*i-2]=a[i]-d,ha[3*i-1]=a[i],ha[3*i]=a[i]+d;
        sort(ha+1,ha+3*n+1);
        int len=unique(ha+1,ha+3*n+1)-ha-1;
        for(int i=1;i<=n;i++)
        {
            l[i]=lower_bound(ha+1,ha+len+1,a[i]-d)-ha;
            r[i]=lower_bound(ha+1,ha+len+1,a[i]+d)-ha;
            a[i]=lower_bound(ha+1,ha+len+1,a[i])-ha;
        }
        for(int i=1;i<=n;i++)
        {
            f[i]=query(l[i],r[i],1,len,1)+1;
            change(a[i],f[i],1,len,1);
            ans=max(ans,f[i]);
        }
        printf("%d\n",ans);
        ans=0;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章