luoojP1030最長跳躍路線

CF474E簡化版
(cf中此題需要輸出答案的方案,此題只需輸出答案)

分析

首先想到的是暴力的dp刷表法和填表法都是很簡單的,這裏不再一一闡述;
不過要做出這題的話首先還是要先學會nlogn的追償上升子序列;之後這題就會用到這個思路的原理;首先離散化,之後就用線段樹或樹狀數組來維護
附上註釋代碼

#include<bits/stdc++.h>
#define N 100005
#define LL long long
#define INF 1e18
#define ls l,mid,i<<1
#define rs mid+1,r,i<<1|1
using namespace std;
int t[N<<2];
void update(int p,int v,int l,int r,int i){
    if(l==r){
        t[i]=v;
        return;
    }
    int mid=l+r>>1;
    if(p<=mid)update(p,v,ls);
    else update(p,v,rs);
    t[i]=max(t[i<<1],t[i<<1|1]);
}//線段樹跟新將p的值跟新成dp;
int query(int st,int ed,int l,int r,int i){
    if(st<=l&&r<=ed)return t[i];
    int ans=0,mid=l+r>>1;
    if(st<=mid)ans=max(ans,query(st,ed,ls));
    if(ed>mid)ans=max(ans,query(st,ed,rs));
    return ans;
}//查詢值(logn)
LL a[N],b[N],k;
int n,dp[N];
int main(){
    scanf("%d%lld",&n,&k);
    for(int i=1;i<=n;i++){
        scanf("%lld",&a[i]);
        b[i]=a[i];
    }
    sort(b+1,b+1+n);//排序離散化
    b[0]=-INF;b[n+1]=INF;//頭尾賦最大最小值
    for(int i=1;i<=n;i++){
        int pos=lower_bound(b,b+2+n,a[i])-b;
        int p1=upper_bound(b,b+2+n,a[i]-k)-b-1;//注意此處要用upper_bound因爲>=所以最右的點爲大於a[i]-k的第一個數減一
        int p2=lower_bound(b,b+2+n,a[i]+k)-b;//道理和上面差不多
        int res=0;
        if(p1>=1)res=max(res,query(1,p1,1,n,1));
        if(p2<=n)res=max(res,query(p2,n,1,n,1));
        dp[i]=res+1;//dp
        update(pos,dp[i],1,n,1);//跟新
    }
    int ans=0;
    for(int i=1;i<=n;i++)
        ans=max(ans,dp[i]);
    printf("%d\n",ans);
    return 0;
}
發佈了59 篇原創文章 · 獲贊 8 · 訪問量 7626
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章