Pillars (Codeforces 474E)
Tags: DP, trees

Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≤ i1 < i2 < ... < ik ≤ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| ≥ d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.

Input: The first line contains two integers n and d (1 ≤ n ≤ 105, 0 ≤ d ≤ 109).The second line contains n numbers h1, h2, ..., hn (1 ≤ hi ≤ 1015).

Output: The first line should contain one integer k, the maximal length of a jump sequence.The second line should contain k integers i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), representing the pillars' indices from the maximal length jump sequence.If there is more than one maximal length jump sequence, print any.

Note: In the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.

Sample Inputs:
5 2
1 3 6 7 4

10 3
2 1 3 6 9 11 7 3 20 18

Sample Outputs:
4
1 2 3 5

6
1 4 6 7 8 9

Solution (Python):
import bisect
from sys import stdin
inf = 1 << 64

class FastIO:

    def __init__(self):
        self.random_seed = 0
        return

    @staticmethod
    def read_int():
        return int(stdin.readline().rstrip())

    @staticmethod
    def read_float():
        return float(stdin.readline().rstrip())

    @staticmethod
    def read_list_ints():
        return list(map(int, stdin.readline().rstrip().split()))

    @staticmethod
    def read_list_ints_minus_one():
        return list(map(lambda x: int(x) - 1, stdin.readline().rstrip().split()))

    @staticmethod
    def read_str():
        return stdin.readline().rstrip()

    @staticmethod
    def read_list_strs():
        return stdin.readline().rstrip().split()

    def get_random_seed(self):
        import random
        self.random_seed = random.randint(0, 10 ** 9 + 7)
        return

    @staticmethod
    def st(x, flush=False):
        return print(x, flush=flush)

    @staticmethod
    def lst(x, flush=False):
        return print(*x, flush=flush)

    @staticmethod
    def max(a, b):
        return a if a > b else b

    @staticmethod
    def min(a, b):
        return a if a < b else b

    @staticmethod
    def ceil(a, b):
        return a // b + int(a % b != 0)

    @staticmethod
    def accumulate(nums):
        n = len(nums)
        pre = [0] * (n + 1)
        for i in range(n):
            pre[i + 1] = pre[i] + nums[i]
        return pre

class PointSetRangeMaxIndex:

    def __init__(self, n, initial=0):
        self.n = n
        self.initial = initial
        self.cover = [initial] * (4 * n)
        self.index = [initial] * (4 * n)
        return

    @classmethod
    def merge(cls, x, y):
        return x if x > y else y

    def _push_up(self, i):
        (a, b) = (self.cover[i << 1], self.cover[i << 1 | 1])
        if a > b:
            (self.cover[i], self.index[i]) = (a, self.index[i << 1])
        else:
            (self.cover[i], self.index[i]) = (b, self.index[i << 1 | 1])
        return

    def build(self, nums):
        stack = [(0, self.n - 1, 1)]
        while stack:
            (s, t, i) = stack.pop()
            if i >= 0:
                if s == t:
                    self.cover[i] = nums[s]
                    self.index[i] = s
                else:
                    stack.append((s, t, ~i))
                    m = s + (t - s) // 2
                    stack.append((s, m, i << 1))
                    stack.append((m + 1, t, i << 1 | 1))
            else:
                i = ~i
                self._push_up(i)
        return

    def get(self):
        stack = [(0, self.n - 1, 1)]
        nums = [0] * self.n
        while stack:
            (s, t, i) = stack.pop()
            if s == t:
                val = self.cover[i]
                nums[s] = val
                continue
            m = s + (t - s) // 2
            stack.append((s, m, i << 1))
            stack.append((m + 1, t, i << 1 | 1))
        return nums

    def point_set_index(self, ind, x, val):
        (s, t, i) = (0, self.n - 1, 1)
        while True:
            if s == t == ind:
                self.cover[i] = val
                self.index[i] = x
                break
            m = s + (t - s) // 2
            if ind <= m:
                (s, t, i) = (s, m, i << 1)
            else:
                (s, t, i) = (m + 1, t, i << 1 | 1)
        while i > 1:
            i //= 2
            self._push_up(i)
        return

    def range_max_index(self, left, right):
        stack = [(0, self.n - 1, 1)]
        ans = self.initial
        ind = -1
        while stack:
            (s, t, i) = stack.pop()
            if left <= s and t <= right:
                if ans < self.cover[i]:
                    (ans, ind) = (self.cover[i], self.index[i])
                continue
            m = s + (t - s) // 2
            if left <= m:
                stack.append((s, m, i << 1))
            if right > m:
                stack.append((m + 1, t, i << 1 | 1))
        return (ans, ind)

class Solution:

    def __init__(self):
        return

    @staticmethod
    def main(ac=FastIO()):
        """"""
        (n, d) = ac.read_list_ints()
        nums = ac.read_list_ints()
        nodes = sorted(set(nums))
        dct = {num: i for (i, num) in enumerate(nodes)}
        m = len(nodes)
        tree = PointSetRangeMaxIndex(m)
        pre = [-1] * n
        for (x, num) in enumerate(nums):
            cur_val = 0
            cur_ind = -1
            i = bisect.bisect_right(nodes, num - d) - 1
            if i >= 0:
                (val, ind) = tree.range_max_index(0, i)
                if val > cur_val:
                    cur_val = val
                    cur_ind = ind
            i = bisect.bisect_left(nodes, num + d)
            if i < m:
                (val, ind) = tree.range_max_index(i, m - 1)
                if val > cur_val:
                    cur_val = val
                    cur_ind = ind
            pre[x] = cur_ind
            tree.point_set_index(dct[num], x, cur_val + 1)
        (ans, ind) = tree.range_max_index(0, m - 1)
        lst = [ind]
        while pre[lst[-1]] != -1:
            lst.append(pre[lst[-1]])
        lst.reverse()
        ac.st(ans)
        ac.lst([x + 1 for x in lst])
        return
Solution().main()

Solution (Python):
from bisect import bisect_left, bisect_right
import sys
readline = sys.stdin.readline

class Segment_Tree:

    def __init__(self, N, f, e, lst=None):
        self.f = f
        self.e = e
        self.N = N
        if lst == None:
            self.segment_tree = [self.e] * 2 * self.N
        else:
            assert len(lst) <= self.N
            self.segment_tree = [self.e] * self.N + [x for x in lst] + [self.e] * (N - len(lst))
            for i in range(self.N - 1, 0, -1):
                self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def __getitem__(self, i):
        if type(i) == int:
            if -self.N <= i < 0:
                return self.segment_tree[i + self.N * 2]
            elif 0 <= i < self.N:
                return self.segment_tree[i + self.N]
            else:
                raise IndexError('list index out of range')
        else:
            (a, b, c) = (i.start, i.stop, i.step)
            if a == None:
                a = self.N
            else:
                a += self.N
            if b == None:
                b = self.N * 2
            else:
                b += self.N
            return self.segment_tree[slice(a, b, c)]

    def __setitem__(self, i, x):
        if -self.N <= i < 0:
            i += self.N * 2
        elif 0 <= i < self.N:
            i += self.N
        else:
            raise IndexError('list index out of range')
        self.segment_tree[i] = x
        while i > 1:
            i >>= 1
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def Build(self, lst):
        for (i, x) in enumerate(lst, self.N):
            self.segment_tree[i] = x
        for i in range(self.N - 1, 0, -1):
            self.segment_tree[i] = self.f(self.segment_tree[i << 1], self.segment_tree[i << 1 | 1])

    def Fold(self, L=None, R=None):
        if L == None:
            L = self.N
        else:
            L += self.N
        if R == None:
            R = self.N * 2
        else:
            R += self.N
        vL = self.e
        vR = self.e
        while L < R:
            if L & 1:
                vL = self.f(vL, self.segment_tree[L])
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.segment_tree[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def Fold_Index(self, L=None, R=None):
        if L == None:
            L = self.N
        else:
            L += self.N
        if R == None:
            R = self.N * 2
        else:
            R += self.N
        if L == R:
            return None
        x = self.Fold(L - self.N, R - self.N)
        while L < R:
            if L & 1:
                if self.segment_tree[L] == x:
                    i = L
                    break
                L += 1
            if R & 1:
                R -= 1
                if self.segment_tree[R] == x:
                    i = R
                    break
            L >>= 1
            R >>= 1
        while i < self.N:
            if self.segment_tree[i] == self.segment_tree[i << 1]:
                i <<= 1
            else:
                i <<= 1
                i |= 1
        i -= self.N
        return i

    def Bisect_Right(self, l=None, f=None):
        if l == self.N:
            return self.N
        if l == None:
            l = 0
        if f(self.Fold(l, self.N)):
            return self.N
        l += self.N
        v = self.e
        while True:
            while l % 2 == 0:
                l >>= 1
            vv = self.f(v, self.segment_tree[l])
            if f(vv):
                v = vv
                l += 1
                if 2 * self.N == l << self.N.bit_length() - l.bit_length() + 1:
                    return self.N
            else:
                while l < self.N:
                    l <<= 1
                    vv = self.f(v, self.segment_tree[l])
                    if f(vv):
                        v = vv
                        l += 1
                return l - self.N

    def Bisect_Left(self, r=None, f=None):
        if r == 0:
            return 0
        if r == None:
            r = self.N
        if f(self.Fold(0, r)):
            return 0
        r += self.N
        v = self.e
        while True:
            r -= 1
            while r > 1 and r % 2:
                r >>= 1
            vv = self.f(self.segment_tree[r], v)
            if f(vv):
                v = vv
                if 2 * self.N == r << self.N.bit_length() - r.bit_length() + 1:
                    return 0
            else:
                while r < self.N:
                    r = 2 * r + 1
                    vv = self.f(self.segment_tree[r], v)
                    if f(vv):
                        v = vv
                        r -= 1
                return r + 1 - self.N

    def __str__(self):
        return '[' + ', '.join(map(str, self.segment_tree[self.N:])) + ']'

def Compress(lst):
    decomp = sorted(list(set(lst)))
    comp = {x: i for (i, x) in enumerate(decomp)}
    return (comp, decomp)
(N, D) = map(int, readline().split())
H = list(map(int, readline().split()))
(comp, decomp) = Compress(H)
le = len(comp)
inf = 1 << 30
dp = Segment_Tree(le, max, -inf, [0] * le)
change = []
(A, B, X, Y) = ([], [], [], [])
for h in H:
    hh = comp[h]
    change.append((hh, dp[hh]))
    dp.Fold(0, bisect_right(decomp, h - D))
    a = bisect_right(decomp, h - D)
    b = bisect_left(decomp, h + D)
    A.append(a)
    B.append(b)
    x = dp.Fold(0, a)
    y = dp.Fold(b, le)
    X.append(x)
    Y.append(y)
    dp[hh] = max(1, x + 1, y + 1, dp[hh])
ans = max((dp[i] for i in range(le)))
print(ans)
ans_lst = []
(l, r) = (0, le)
for i in range(N - 1, -1, -1):
    if l <= change[i][0] < r:
        if X[i] + 1 == ans:
            ans -= 1
            ans_lst.append(i + 1)
            (l, r) = (0, A[i])
        elif Y[i] + 1 == ans:
            ans -= 1
            ans_lst.append(i + 1)
            (l, r) = (B[i], le)
print(*ans_lst[::-1])

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

class SegTree:

    def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
        self._op = op
        self._e = e
        if isinstance(v, int):
            v = [e] * v
        self._n = len(v)
        self._log = (self._n - 1).bit_length()
        self._size = 1 << self._log
        self._d = [e] * (2 * self._size)
        for i in range(self._n):
            self._d[self._size + i] = v[i]
        for i in range(self._size - 1, 0, -1):
            self._update(i)

    def set(self, p: int, x: typing.Any) -> None:
        assert 0 <= p < self._n
        p += self._size
        self._d[p] = x
        for i in range(1, self._log + 1):
            self._update(p >> i)

    def get(self, p: int) -> typing.Any:
        assert 0 <= p < self._n
        return self._d[p + self._size]

    def prod(self, left: int, right: int) -> typing.Any:
        assert 0 <= left <= right <= self._n
        sml = self._e
        smr = self._e
        left += self._size
        right += self._size
        while left < right:
            if left & 1:
                sml = self._op(sml, self._d[left])
                left += 1
            if right & 1:
                right -= 1
                smr = self._op(self._d[right], smr)
            left >>= 1
            right >>= 1
        return self._op(sml, smr)

    def all_prod(self) -> typing.Any:
        return self._d[1]

    def max_right(self, left: int, f: typing.Callable[[typing.Any], bool]) -> int:
        assert 0 <= left <= self._n
        assert f(self._e)
        if left == self._n:
            return self._n
        left += self._size
        sm = self._e
        first = True
        while first or left & -left != left:
            first = False
            while left % 2 == 0:
                left >>= 1
            if not f(self._op(sm, self._d[left])):
                while left < self._size:
                    left *= 2
                    if f(self._op(sm, self._d[left])):
                        sm = self._op(sm, self._d[left])
                        left += 1
                return left - self._size
            sm = self._op(sm, self._d[left])
            left += 1
        return self._n

    def min_left(self, right: int, f: typing.Callable[[typing.Any], bool]) -> int:
        assert 0 <= right <= self._n
        assert f(self._e)
        if right == 0:
            return 0
        right += self._size
        sm = self._e
        first = True
        while first or right & -right != right:
            first = False
            right -= 1
            while right > 1 and right % 2:
                right >>= 1
            if not f(self._op(self._d[right], sm)):
                while right < self._size:
                    right = 2 * right + 1
                    if f(self._op(self._d[right], sm)):
                        sm = self._op(self._d[right], sm)
                        right -= 1
                return right + 1 - self._size
            sm = self._op(self._d[right], sm)
        return 0

    def _update(self, k: int) -> None:
        self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])

def main():
    (n, d) = MII()
    nums = LII()
    vs = sorted(set(sorted(nums)))
    seg = SegTree(max, 0, len(vs))
    dp = [1] * n
    prev = [-1] * n
    for i in range(n):
        v = -1
        l = bisect.bisect_right(vs, nums[i] - d) - 1
        if l >= 0:
            v = max(v, seg.prod(0, l + 1))
        r = bisect.bisect_left(vs, nums[i] + d)
        if r < len(vs):
            v = max(v, seg.prod(r, len(vs)))
        (dp[i], prev[i]) = divmod(v, n + 1)
        dp[i] += 1
        prev[i] -= 1
        seg.set(bisect.bisect_left(vs, nums[i]), dp[i] * (n + 1) + i + 1)
    print(max(dp))
    ans = [dp.index(max(dp))]
    while prev[ans[-1]] != -1:
        ans.append(prev[ans[-1]])
    print(*(x + 1 for x in reversed(ans)))
    return
t = 1
for _ in range(t):
    main()