Official

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

claude5.5opus-high

Overview

This problem asks us to find the maximum possible sum of scores of a subsequence of exhibits chosen in increasing order of index, such that the difference in height between adjacent exhibits lies in \([L,R]\), and the direction of heights strictly alternates between going up and going down. We solve this by using dynamic programming with the state representing “whether the last transition was going up or going down”, accelerated using segment trees indexed by height.

Analysis

DP State

For a subsequence ending at exhibit \(i\), whether the immediately preceding transition was “up” or “down” determines the next allowed transition. Therefore, we consider the following two values:

  • \(U_i\): The maximum score of a subsequence ending at exhibit \(i\) whose last transition is “up”, or a subsequence consisting only of \(i\).
  • \(D_i\): The maximum score of a subsequence ending at exhibit \(i\) whose last transition is “down”, or a subsequence consisting only of \(i\).

Since a subsequence consisting solely of exhibit \(i\) can transition in either direction next, we include it in both \(U_i\) and \(D_i\).

From the constraints, since \(L \ge 1\), adjacent heights can never be equal. Thus, the sign of the difference is always strictly positive or negative.

Transitions

  • Transitioning up from \(j\) to \(i\): The condition is \(A_i - R \le A_j \le A_i - L\). To strictly alternate directions, the transition to \(j\) must have been “down”, or \(j\) must be the first element. Thus: $\(\mathrm{up}_i = B_i + \max_{j<i,\ A_j\in[A_i-R,\,A_i-L]} D_j\)$
  • Transitioning down from \(j\) to \(i\): The condition is \(A_i + L \le A_j \le A_i + R\). The transition to \(j\) must have been “up”, or \(j\) must be the first element. Thus: $\(\mathrm{down}_i = B_i + \max_{j<i,\ A_j\in[A_i+L,\,A_i+R]} U_j\)$

Finally, taking into account the case where \(i\) is chosen alone, we summarize as: $\(U_i=\max(B_i,\mathrm{up}_i),\qquad D_i=\max(B_i,\mathrm{down}_i)\)$

The answer is the maximum over all \(U_i, D_i\) for all \(i\), along with \(0\) corresponding to choosing an empty subsequence.

Issues with the Naive Approach

Checking all preceding indices \(j\) for each \(i\) takes \(O(N^2)\) time. For \(N=200000\), this requires approximately \(4\times 10^{10}\) operations, leading to TLE.

Key Idea for Optimization

The transition conditions are: “\(j<i\)” and “\(A_j\) falls within a certain interval”.

  • By processing \(i\) in increasing order of index and only recording already processed values, the condition “\(j<i\)” is automatically satisfied.
  • The remaining condition—finding the maximum value over all \(j\) such that \(A_j\) falls into an interval \([x,y]\)—is precisely a range maximum query indexed by height.

Since heights can be as large as \(10^9\), we compress the coordinates and maintain the values using segment trees. We prepare two segment trees: one for \(D\) and one for \(U\). If there are multiple exhibits with the same height, we only need to keep the larger value at that position.

Concrete Example

Consider the case where \(L=1, R=3\), heights \(A=(2,4,1,3)\), and scores \(B=(5,-1,4,2)\).

\(i\) Calculation \(U_i\) \(D_i\)
1 Single element only \(5\) \(5\)
2 The maximum \(D\) in height range \([1,3]\) is \(D_1=5\), so \(\mathrm{up}_2=-1+5=4\). No valid previous element for going down \(4\) \(-1\)
3 The maximum \(U\) in height range \([2,4]\) is \(\max(U_1,U_2)=5\), so \(\mathrm{down}_3=4+5=9\) \(4\) \(9\)
4 The maximum \(D\) in height range \([0,2]\) is \(\max(D_1,D_3)=9\), so \(\mathrm{up}_4=2+9=11\) \(11\) \(\cdots\)

The answer is \(11\), achieved by choosing heights \(2 \to 1 \to 3\) (down, then up).

Algorithm

  1. Coordinate-compress the heights \(A\).
  2. Prepare two segment trees that support range maximum queries (TD for \(D\) and TU for \(U\)), initialized with \(-\infty\).
  3. For \(i=1,\ldots,N\) in order, perform the following:
    • Use binary search to find the compressed index range corresponding to the height interval \([A_i-R, A_i-L]\). Query the maximum value in this range using TD, and compute \(\mathrm{up}_i\). If there are no values in this range, set it to \(-\infty\).
    • Similarly, query the maximum value in the range corresponding to the height interval \([A_i+L, A_i+R]\) using TU, and compute \(\mathrm{down}_i\).
    • Set \(U_i=\max(B_i,\mathrm{up}_i)\) and \(D_i=\max(B_i,\mathrm{down}_i)\), and update the overall answer.
    • At the position corresponding to height \(A_i\), update TU with \(U_i\) and TD with \(D_i\) (taking the maximum).
  4. Print the answer (initialized to \(0\)).

Complexity

  • Time complexity: \(O(N\log N)\) (sorting for coordinate compression, and \(O(\log N)\) per \(i\) for binary searches and segment tree operations)
  • Space complexity: \(O(N)\)

Implementation Notes

  • Initial Value of the Answer: Since we have the option of choosing nothing (empty subsequence), the answer should be initialized to \(0\). This ensures that if all scores are negative, \(0\) is correctly output.

  • Handling Sentinels: Use a sufficiently small value such as \(-2^{62}\) for \(-\infty\). If the range is empty or contains no valid values, determine this with best > NEG and keep it as \(-\infty\) without adding \(B_i\). Adding \(B_i\) to \(-\infty\) could lead to non-existent transitions being incorrectly considered valid.

  • Finding Query Ranges: Using bisect_left(xs, a-R) and bisect_right(xs, a-L), one can directly obtain the compressed index range corresponding to the closed interval \([a-R,a-L]\) as a half-open interval.

  • Segment Tree Implementation: To run fast in Python, a non-recursive (bottom-up) segment tree is used. In point updates, terminating early when the parent value no longer changes helps optimize constant-factor performance.

  • Handling Equal Heights: Exhibits with the same height correspond to the same leaf in the segment tree. Thus, updating only when the new value is larger (max update) handles duplicates correctly.

    Source Code

import sys
from bisect import bisect_left, bisect_right

def main():
    data = sys.stdin.buffer.read().split()
    n = int(data[0]); L = int(data[1]); R = int(data[2])
    A = [int(x) for x in data[3:3+2*n:2]]
    B = [int(x) for x in data[4:4+2*n:2]]
    xs = sorted(set(A))
    m = len(xs)
    size = 1
    while size < m:
        size *= 2
    NEG = -(1 << 62)
    TD = [NEG] * (2 * size)  # stores D[j] = max(B_j, down[j])
    TU = [NEG] * (2 * size)  # stores U[j] = max(B_j, up[j])
    idx = {v: i for i, v in enumerate(xs)}
    ans = 0
    for i in range(n):
        a = A[i]; b = B[i]
        # up: previous A_j in [a-R, a-L], use TD
        l = bisect_left(xs, a - R) + size
        r = bisect_right(xs, a - L) + size
        best = NEG
        while l < r:
            if l & 1:
                v = TD[l]
                if v > best: best = v
                l += 1
            if r & 1:
                r -= 1
                v = TD[r]
                if v > best: best = v
            l >>= 1; r >>= 1
        up = b + best if best > NEG else NEG
        # down: previous A_j in [a+L, a+R], use TU
        l = bisect_left(xs, a + L) + size
        r = bisect_right(xs, a + R) + size
        best = NEG
        while l < r:
            if l & 1:
                v = TU[l]
                if v > best: best = v
                l += 1
            if r & 1:
                r -= 1
                v = TU[r]
                if v > best: best = v
            l >>= 1; r >>= 1
        down = b + best if best > NEG else NEG
        U = up if up > b else b
        D = down if down > b else b
        if U > ans: ans = U
        if D > ans: ans = D
        p = idx[a] + size
        if TU[p] < U:
            TU[p] = U
            q = p >> 1
            while q:
                x = TU[2*q]; y = TU[2*q+1]
                nv = x if x > y else y
                if TU[q] == nv:
                    break
                TU[q] = nv
                q >>= 1
        if TD[p] < D:
            TD[p] = D
            q = p >> 1
            while q:
                x = TD[2*q]; y = TD[2*q+1]
                nv = x if x > y else y
                if TD[q] == nv:
                    break
                TD[q] = nv
                q >>= 1
    print(ans)

main()

This editorial was generated by claude5.5opus-high.

posted:
last update: