hdu4521 小明系列问题——小明序列(线段树做法)

时间:2021-04-10 19:29:07
/* ***********************************************
Author        :fisty
Created Time  :2014/12/31 22:21:52
File Name     :hud4521.cpp
************************************************ */

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define MAX_N 500010
int a[MAX_N], imx[MAX_N];

struct segtree{
    struct node{
        int left, right;
        int maxx;
        int mid(){
            return (left+(right - left)/2);
        }
    }tree[MAX_N*4];
    void build(int l ,int r ,int k){
        tree[k].left = l;tree[k].right = r;
        tree[k].maxx = 0;
        if(l != r){
            int mid = tree[k].mid();
            build(l, mid, k<<1);
            build(mid+1, r, k<<1|1);
        }
    }
    void update(int  pos, int k, int val){
        if(tree[k].left == tree[k].right) tree[k].maxx = max(tree[k].maxx, val);
        else{
            int mid = tree[k].mid();
            if(pos <= mid) update(pos, k << 1, val);
            if(pos > mid) update(pos, k << 1 | 1, val);
            tree[k].maxx = max(tree[k<<1].maxx,tree[k<<1|1].maxx);
        }
    }
    int query(int l, int r, int k){
        if(l <= tree[k].left && tree[k].right <= r) return tree[k].maxx;
        else{
            int v1 = 0, v2 =0;
            int mid = tree[k].mid();
            if(l <= mid)   v1 = query(l, r, k << 1);
            if(r > mid)           v2 = query(l, r, k << 1|1);
            return max(v1, v2);
        }
    }

}seg;
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    //cin.tie(0);
    //std::ios::sync_with_stdio(false);
    int n, d;
    while(scanf("%d%d", &n, &d) != EOF){
        int end = 0, ans = 0;
        for(int i = 0;i < n; i++){
            scanf("%d", &a[i]);
            end = max(end, a[i]);
        }
        seg.build(0, end, 1);
        for(int i = 0;i < n; i++){
            if(i - d - 1 >= 0) seg.update(a[i-d-1],1,imx[i-d-1]);   //当i-d-1>=0 时,将第a[i-d-1]更新
            if(a[i] > 0)  imx[i] = seg.query(0, a[i]-1, 1) + 1; //以a[i]结尾的最长序列
            else imx[i] = 1;
            ans = max(imx[i], ans);                             //找到最长序列
        }
        printf("%d\n", ans);
    }
    return 0;
}