E - 上下に跳ぶ展示順 / Exhibition Order Jumping Up and Down Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
We choose exhibits in increasing order of their indices to maximize the total score of a sequence whose heights alternate between “increasing” and “decreasing”. We formulate dynamic programming that keeps track of the last transition direction in the state, and optimize the transitions using coordinate compression and segment trees.
Analysis
1. Keeping Track of the Last Transition Direction
Which exhibit can be appended after exhibit \(i\) depends not only on the last height, but also on whether the previous step went up or down.
Therefore, we define the following states:
- \(up_i\): the maximum score of a sequence ending at exhibit \(i\) where the last step is “increasing” (going up)
- \(down_i\): the maximum score of a sequence ending at exhibit \(i\) where the last step is “decreasing” (going down)
Here, a sequence consisting of only a single exhibit is included in both states. This allows us to handle cases where the first transition goes up or down using the same formula.
2. Transition Sources Can Be Represented as Height Ranges
Consider the case where we append exhibit \(i\) after exhibit \(j\) such that the last step is “increasing”.
Since we select exhibits in index order, we require \(j<i\). In addition, the condition on heights is:
\(L\leq A_i-A_j\leq R\)
Rearranging this gives:
\(A_i-R\leq A_j\leq A_i-L\)
Because the step before going up must have been going down, the source of this transition is \(down_j\).
Similarly, when the last step is “decreasing”, we transition from \(up_j\) satisfying:
\(A_i+L\leq A_j\leq A_i+R\)
Therefore, the recurrence relations are as follows:
\(up_i=B_i+\max\left(\{0\}\cup\{down_j\mid j<i,\ A_i-R\leq A_j\leq A_i-L\}\right)\)
\(down_i=B_i+\max\left(\{0\}\cup\{up_j\mid j<i,\ A_i+L\leq A_j\leq A_i+R\}\right)\)
Here, including \(0\) as a candidate corresponds to starting a new sequence with only exhibit \(i\), without extending any previous sequence.
3. Efficiently Finding the Range Maximum
Checking all \(j<i\) for each \(i\) would take \(O(N^2)\) time, which is too slow for \(N\leq 200000\).
What we need are the following operations over past exhibits:
- Query the maximum \(down\) value within a specified range of heights
- Query the maximum \(up\) value within a specified range of heights
- Register the new state at the current height
These operations can be processed using segment trees that maintain range maximums.
However, since heights can be up to \(10^9\), they cannot be directly used as array indices. Therefore, we perform coordinate compression by sorting only the heights that actually appear in ascending order.
Algorithm
1. Coordinate Compression on Heights
Sort all \(A_i\) with duplicates removed to construct an array coords.
For example, if the heights are \([10,3,7,10]\), then:
coords = [3, 7, 10]
and the heights \(3,7,10\) are managed by indices \(0,1,2\), respectively.
Note that differences between compressed indices do not equal differences between the original heights. When checking the height condition, we construct the range using the original heights and find the corresponding range of indices using binary search.
2. Prepare Two Segment Trees
Initialize the following segment trees with all elements set to \(0\):
up_tree: maintains the maximum of processed \(up\) values ending at each heightdown_tree: maintains the maximum of processed \(down\) values ending at each height
Strictly speaking, for each height, we store \(\max(\text{registered maximum}, 0)\).
We do not need to store negative values because starting a new sequence with only the current exhibit yields a higher score than appending it to a sequence with a negative score. Since a single-exhibit sequence can be treated as either state, we do not lose any subsequent transitions by doing so.
3. Process Exhibits in Index Order
Let \(a\) and \(b\) be the height and score of the current exhibit, respectively.
Computing the “Increasing” State
Query down_tree for the maximum value among states whose heights fall in the range \([a-R,a-L]\), and add \(b\) to it.
For example, if \(a=10,L=2,R=4\), the previous height must be in the range \([6,8]\).
The index range is determined by the following binary searches:
- Left bound:
bisect_left(coords, a - R) - Right bound:
bisect_right(coords, a - L)
We query the interval from this left bound (inclusive) to the right bound (exclusive). If the maximum value is \(0\), it corresponds to choosing only the current exhibit.
Computing the “Decreasing” State
Similarly, query up_tree for the maximum value among states whose heights fall in the range \([a+L,a+R]\), and add \(b\) to it.
The index range is determined by:
- Left bound:
bisect_left(coords, a + L) - Right bound:
bisect_right(coords, a + R)
Updating the Answer and Segment Trees
Update the answer with the computed up and down values.
Then, update the position corresponding to height \(a\) as follows:
up_tree: the maximum of the current value andupdown_tree: the maximum of the current value anddown
Even if there are multiple exhibits with the same height, it suffices to keep only the one with the maximum score for the same direction. This is because future transition conditions depend only on the ending height and direction, not on the specific past index.
4. Output the Answer
Initialize the answer to \(0\). This also accounts for the case where no exhibit is chosen.
When processing each exhibit, the segment trees contain only the states of earlier exhibits. By querying the maximum value satisfying the height and direction conditions, we correctly compute the transitions described above. Therefore, the maximum over all states and \(0\) is the desired answer.
Complexity
- Time complexity: \(O(N\log N)\)
- Space complexity: \(O(N)\)
Coordinate compression takes \(O(N\log N)\) time, and for each exhibit, binary search, range maximum query, and point update each take \(O(\log N)\) time.
Implementation Points
Compute both states before updating
To prevent the current exhibit from being used as its own transition source, only register the values into the segment trees after completing bothupanddowncalculations.Converting closed intervals to half-open intervals
The height conditions are inclusive (closed intervals). Usingbisect_leftfor the left endpoint andbisect_rightfor the right endpoint converts them into half-open intervals suitable for segment tree queries.Do not overwrite at the same height; keep the maximum
Even if a lower-scoring state appears later with the same height, do not overwrite a better state from before.Early termination of tree updates in the code
Since updates only increase values, the new value can be propagated from the leaf to its ancestors. If neither tree’s value changes at a certain node, the ancestors above will not change either, so the update can be terminated early.Large integers needed for total score
The answer can be up to \(2\times 10^{14}\). Python handles arbitrarily large integers automatically, but in other languages, a \(64\)-bit integer type should be used.Source Code
import sys
from bisect import bisect_left, bisect_right
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
n, L, R = data[0], data[1], data[2]
heights = data[3::2]
scores = data[4::2]
del data
coords = sorted(set(heights))
positions = {a: i for i, a in enumerate(coords)}
size = 1
while size < len(coords):
size <<= 1
up_tree = [0] * (size << 1)
down_tree = [0] * (size << 1)
answer = 0
for a, b in zip(heights, scores):
left = bisect_left(coords, a - R) + size
right = bisect_right(coords, a - L) + size
best = 0
while left < right:
if left & 1:
value = down_tree[left]
if value > best:
best = value
left += 1
if right & 1:
right -= 1
value = down_tree[right]
if value > best:
best = value
left >>= 1
right >>= 1
up = best + b
left = bisect_left(coords, a + L) + size
right = bisect_right(coords, a + R) + size
best = 0
while left < right:
if left & 1:
value = up_tree[left]
if value > best:
best = value
left += 1
if right & 1:
right -= 1
value = up_tree[right]
if value > best:
best = value
left >>= 1
right >>= 1
down = best + b
if up > answer:
answer = up
if down > answer:
answer = down
node = positions[a] + size
while node:
changed = False
if up > up_tree[node]:
up_tree[node] = up
changed = True
if down > down_tree[node]:
down_tree[node] = down
changed = True
if not changed:
break
node >>= 1
print(answer)
if __name__ == "__main__":
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: