【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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值