CF474E Pillars(dp+树状数组)

首先我们有一个显然的 O(n2) dp。倒着做即可。
考虑如何优化,对于第i个点,我其实是在i+1~n中的权值>=x+d和权值<=x-d的点中选一个最大的来转移,我们可以用离散化+两个树状数组来实现查询前缀后缀最大值。复杂度 O(nlogn)

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
#define N 100010
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline ll read(){
    ll x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,m,d,c1[N],c2[N],ans[N],to[N];
ll a[N],aa[N];
inline int Max(int x,int y){return ans[x]<ans[y]?y:x;}
inline void add1(int x,int val){
    for(;x<=m;x+=x&-x) c1[x]=Max(c1[x],val);
}
inline void add2(int x,int val){
    for(;x<=m;x+=x&-x) c2[x]=Max(c2[x],val);
}
inline int ask1(int x){
    int res=0;for(;x;x-=x&-x) res=Max(res,c1[x]);return res;
}
inline int ask2(int x){
    int res=0;for(;x;x-=x&-x) res=Max(res,c2[x]);return res;
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();d=read();
    for(int i=1;i<=n;++i) a[i]=aa[i]=read();
    sort(aa+1,aa+n+1);m=unique(aa+1,aa+n+1)-aa-1;
    for(int i=n;i>=1;--i){
        int x=lower_bound(aa+1,aa+m+1,a[i]+d)-aa;
        int y=upper_bound(aa+1,aa+m+1,a[i]-d)-aa-1;
        int res=Max(ask1(y),ask2(m-x+1));
        ans[i]=ans[res]+1;to[i]=res;int pos=lower_bound(aa+1,aa+m+1,a[i])-aa;
        add1(pos,i);add2(m-pos+1,i);
    }int res=0;for(int i=1;i<=n;++i) res=Max(res,i);
    printf("%d\n",ans[res]);
    while(res){printf("%d ",res);res=to[res];}
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值