Official

E - 上下に跳ぶ展示順 / Exhibition Order Jumping Up and Down Editorial by admin Editorial for printing

Gemini 3.8 Flash (High)

Overview

This problem asks us to choose a subsequence from a given sequence such that “the absolute difference between adjacent elements is within the range \([L, R]\)” and “the changes in value (going up / going down) alternate,” maximizing the total score. By optimizing the dynamic programming (DP) transitions using coordinate compression and segment trees, this problem can be solved in \(O(N \log N)\).


Analysis

Naive Dynamic Programming (\(O(N^2)\))

First, let us consider dynamic programming focusing on the end of the subsequence. Depending on whether exhibit \(i\) was reached by “going up” or “going down” from the previous element, the conditions for the next element that can be chosen will differ. Therefore, we define the following two states:

  • \(dp_{\mathrm{up}}[i]\): The maximum score when ending at exhibit \(i\) with the last move being “going up”
  • \(dp_{\mathrm{down}}[i]\): The maximum score when ending at exhibit \(i\) with the last move being “going down”

Letting exhibit \(j\) (\(j < i\)) be the exhibit immediately preceding exhibit \(i\), the transitions are as follows:

  1. Reaching \(i\) by going up
    • The height of \(i\) must be greater than the height of \(j\), and their difference must be within the range \([L, R]\).
    • That is, for \(j\) satisfying \(A_i - R \le A_j \le A_i - L\), \(dp_{\mathrm{up}}[i] = \max(dp_{\mathrm{down}}[j], B_j) + B_i\)
  2. Reaching \(i\) by going down
    • The height of \(i\) must be lower than the height of \(j\), and their difference must be within the range \([L, R]\).
    • That is, for \(j\) satisfying \(A_i + L \le A_j \le A_i + R\), \(dp_{\mathrm{down}}[i] = \max(dp_{\mathrm{up}}[j], B_i) + B_i\)
  • Note: Since it is possible to select only a single element and start from it (where exhibit \(j\) is the first element of the sequence), the standalone score \(B_j\) is also a candidate for the previous state’s score.

Performing these transitions naively requires searching over all \(j < i\) for each \(i\), resulting in a time complexity of \(O(N^2)\), which will exceed the time limit (TLE) under the constraint \(N \le 200000\).

Optimization with Data Structures

Summarizing the transition conditions: - By processing \(i\) in order from \(1\), the condition \(j < i\) is naturally satisfied. - The condition takes the form of “finding the maximum value among elements where \(A_j\) falls within a certain interval” (Range Maximum Query). - For the “going up” transition, we need the maximum of \(\max(dp_{\mathrm{down}}[j], B_j)\) over \(A_j \in [A_i - R, A_i - L]\). - For the “going down” transition, we need the maximum of \(\max(dp_{\mathrm{up}}[j], B_j)\) over \(A_j \in [A_i + L, A_i + R]\).

Although the values of \(A_i\) can be up to \(10^9\), there are at most \(N\) distinct values that appear. Therefore, by performing coordinate compression and using segment trees, we can perform range maximum queries and point updates in \(O(\log N)\).


Algorithm

We prepare two segment trees: - tree1: A segment tree maintaining information for the next “going up” transition (i.e., values where the previous move was “going down”, or starting a sequence here), indexed by height \(A\). - tree2: A segment tree maintaining information for the next “going down” transition, indexed by height \(A\).

Detailed Steps

  1. Coordinate Compression: Sort all values appearing in array \(A\) and remove duplicates to create an array coords.
  2. Segment Tree Initialization: Initialize all elements to a sufficiently small value (\(-\infty\)).
  3. Process sequentially for \(i = 1, \dots, N\):
    • Going up transition:
      • Use binary search to find the index range corresponding to the height range \([A_i - R, A_i - L]\) of the previous element.
      • Query tree1 for the maximum value \(m_1\) in that range.
      • If a valid value exists, set \(dp_{\mathrm{up}} = m_1 + B_i\).
    • Going down transition:
      • Use binary search to find the index range corresponding to the height range \([A_i + L, A_i + R]\) of the previous element.
      • Query tree2 for the maximum value \(m_2\) in that range.
      • If a valid value exists, set \(dp_{\mathrm{down}} = m_2 + B_i\).
    • Update the answer:
      • Update the overall maximum score using the case of choosing exhibit \(i\) alone (\(B_i\)), \(dp_{\mathrm{up}}\), and \(dp_{\mathrm{down}}\).
    • Update the segment trees:
      • For the next “going up” transition, update tree1 at position \(A_i\) with \(\max(dp_{\mathrm{down}}, B_i)\).
      • For the next “going down” transition, update tree2 at position \(A_i\) with \(\max(dp_{\mathrm{up}}, B_i)\).
  4. Output the answer: Since choosing nothing (score \(0\)) is also allowed, output \(\max(0, \text{overall maximum})\).

Complexity

  • Time Complexity: \(O(N \log N)\)
    • Coordinate compression (sorting and removing duplicates) takes \(O(N \log N)\).
    • For each element \(i\), binary search as well as segment tree range queries and point updates are each performed a constant number of times. Each of these takes \(O(\log N)\).
    • In total, the time complexity is \(O(N \log N)\), which comfortably runs within the time limit.
  • Space Complexity: \(O(N)\)
    • The length of the coordinate-compressed array is at most \(N\), and the sizes of the segment trees and arrays storing the input data are \(O(N)\).

Implementation Points

  • Handling the case of choosing nothing: By initializing the total score to 0, the option of “choosing nothing (score \(0\))” is naturally accounted for. In addition, even if all \(B_i\) are negative, \(0\) will be correctly output.

  • Handling the case of choosing only one element: When updating the segment trees, to include the case of starting a new sequence at exhibit \(i\), register them as val_to_up = max(dp_down, B_i) and val_to_down = max(dp_up, B_i).

  • Search range for range queries: By using Python’s bisect_left and bisect_right, the correct half-open interval \([l, r)\) can be efficiently obtained even if \(A_i \pm L\) or \(A_i \pm R\) does not exist in coords.

    Source Code

import sys
from bisect import bisect_left, bisect_right

def main():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    N = int(input_data[0])
    L = int(input_data[1])
    R = int(input_data[2])
    
    A = [0] * N
    B = [0] * N
    idx = 3
    for i in range(N):
        A[i] = int(input_data[idx])
        B[i] = int(input_data[idx+1])
        idx += 2
        
    coords = sorted(list(set(A)))
    M = len(coords)
    
    size = 1
    while size < M:
        size <<= 1
        
    INF = 10**18
    tree1 = [-INF] * (2 * size)
    tree2 = [-INF] * (2 * size)
    
    ans = 0
    
    for a, b in zip(A, B):
        # 1. DP_up
        # 직전 값 A_j が [a - R, a - L] の範囲にあるものを探す
        l1 = bisect_left(coords, a - R)
        r1 = bisect_right(coords, a - L)
        dp_up = -INF
        if l1 < r1:
            ql = l1 + size
            qr = r1 + size
            m1 = -INF
            while ql < qr:
                if ql & 1:
                    if tree1[ql] > m1:
                        m1 = tree1[ql]
                    ql += 1
                if qr & 1:
                    qr -= 1
                    if tree1[qr] > m1:
                        m1 = tree1[qr]
                ql >>= 1
                qr >>= 1
            if m1 > -INF:
                dp_up = m1 + b
                
        # 2. DP_down
        # 직전 값 A_j が [a + L, a + R] の範囲にあるものを探す
        l2 = bisect_left(coords, a + L)
        r2 = bisect_right(coords, a + R)
        dp_down = -INF
        if l2 < r2:
            ql = l2 + size
            qr = r2 + size
            m2 = -INF
            while ql < qr:
                if ql & 1:
                    if tree2[ql] > m2:
                        m2 = tree2[ql]
                    ql += 1
                if qr & 1:
                    qr -= 1
                    if tree2[qr] > m2:
                        m2 = tree2[qr]
                ql >>= 1
                qr >>= 1
            if m2 > -INF:
                dp_down = m2 + b
                
        if b > ans:
            ans = b
        if dp_up > ans:
            ans = dp_up
        if dp_down > ans:
            ans = dp_down
            
        # 次のステップのための最大値を登録
        val_to_up = max(dp_down, b)
        val_to_down = max(dp_up, b)
        
        pos = bisect_left(coords, a)
        
        # セグ木1の更新 (次は上がる遷移を待つ)
        p = pos + size
        if val_to_up > tree1[p]:
            tree1[p] = val_to_up
            p >>= 1
            while p > 0:
                nxt = tree1[p << 1]
                r_val = tree1[(p << 1) | 1]
                if r_val > nxt:
                    nxt = r_val
                if nxt == tree1[p]:
                    break
                tree1[p] = nxt
                p >>= 1
                
        # セグ木2の更新 (次は下がる遷移を待つ)
        p = pos + size
        if val_to_down > tree2[p]:
            tree2[p] = val_to_down
            p >>= 1
            while p > 0:
                nxt = tree2[p << 1]
                r_val = tree2[(p << 1) | 1]
                if r_val > nxt:
                    nxt = r_val
                if nxt == tree2[p]:
                    break
                tree2[p] = nxt
                p >>= 1

    print(ans)

if __name__ == '__main__':
    main()

This editorial was generated by gemini-3.8-flash-high.

posted:
last update: