Official

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

Gemini 3.8 Flash (High)

Overview

In this problem, we need to find the maximum possible total score by choosing exhibits such that the height difference between consecutive chosen items is within the range \([L, R]\), and the heights alternate between “increasing” and “decreasing”.

By considering dynamic programming (DP) where the state tracks the previous direction of movement (increased or decreased), and combining it with a segment tree and coordinate compression, we can solve this problem efficiently in \(O(N \log N)\) time.


Analysis

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

First, consider a dynamic programming (DP) approach where we process the exhibits from left to right. Since the chosen items must alternate between increasing and decreasing heights, we need to track whether the previous step was an increase or a decrease.

  • \(dp_{\mathrm{up}}[i]\): The maximum score when exhibit \(i\) is chosen, and its height increased from the previous exhibit (\(i\) is a peak).
  • \(dp_{\mathrm{down}}[i]\): The maximum score when exhibit \(i\) is chosen, and its height decreased from the previous exhibit (\(i\) is a valley).

Let \(j\) (\(j < i\)) be the exhibit chosen immediately before exhibit \(i\). The transitions are as follows: 1. When increasing to \(i\) (\(A_j < A_i\)): We transition from the \(j\) that maximizes \(dp_{\mathrm{down}}[j]\) subject to \(A_i - R \le A_j \le A_i - L\). 2. When decreasing to \(i\) (\(A_j > A_i\)): We transition from the \(j\) that maximizes \(dp_{\mathrm{up}}[j]\) subject to \(A_i + L \le A_j \le A_i + R\). 3. When choosing \(i\) as the very first exhibit: Even without a valid preceding element, we can choose exhibit \(i\) alone (giving a score of \(B_i\)). From here, the transition to the next exhibit can be either an increase or a decrease.

However, naively checking all \(j < i\) for each \(i\) takes \(O(N^2)\) time, which results in Time Limit Exceeded (TLE) under the constraint \(N \le 200000\).

Optimization Using Segment Trees

Looking closely at the conditions for the transition source, we can summarize them as follows: - \(j < i\) - The height of the previous exhibit \(A_j\) lies within a specific interval - We want to retrieve the maximum DP value within that interval

Processing \(i\) in order of \(1, 2, \ldots, N\) naturally satisfies the condition \(j < i\). Therefore, if we have a data structure indexed by height \(A\) that maintains the maximum DP value for each height, we can perform Range Maximum Queries (RMQ) efficiently. A segment tree is well-suited for this purpose.

However, since the heights \(A_i\) can be as large as \(10^9\), they cannot be directly used as array indices. By applying coordinate compression to the values of \(A_i\) in advance, we can reduce the size of the segment tree to \(O(N)\), which is at most the number of elements.


Algorithm

  1. Coordinate Compression: Sort the values appearing in array \(A\) and remove duplicates to create the coordinate compression array coords.
  2. Preparing the Segment Trees: Prepare two segment trees (supporting RMQ). All initial values are set to \(-\infty\).
    • seg_up: Stores the maximum value for the state where the last movement was an “increase” (peak), indexed by height.
    • seg_down: Stores the maximum value for the state where the last movement was a “decrease” (valley), indexed by height.
  3. Updating the DP: Process exhibits \(i = 0, 1, \dots, N-1\) in order:
    • Calculate decreasing transition: Find the maximum value in seg_up within the height range \([A_i + L, A_i + R]\), and add \(B_i\).
    • Calculate increasing transition: Find the maximum value in seg_down within the height range \([A_i - R, A_i - L]\), and add \(B_i\).
    • Consider starting point (length 1): To account for sequences starting at exhibit \(i\) alone (score \(B_i\)), take the maximum between each calculated value and \(B_i\):
      • Candidate for \(i\) being a valley (next is an increase): \(\max(B_i, dp_{\mathrm{down}})\)
      • Candidate for \(i\) being a peak (next is a decrease): \(\max(B_i, dp_{\mathrm{up}})\)
    • Update the answer: Update the overall maximum score with these candidate values, as well as \(0\) (the case where nothing is chosen).
    • Register into the Segment Trees: At the coordinate-compressed index corresponding to \(A_i\), update seg_down with the valley candidate value and seg_up with the peak candidate value.
  4. Output the maximum value found after processing all elements.

Complexity

  • Time Complexity: \(O(N \log N)\)
    • Coordinate compression takes \(O(N \log N)\) time.
    • For each exhibit \(i\), finding the query range via binary search takes \(O(\log N)\) time, and the segment tree range query and point update take \(O(\log N)\) time. Since this is performed \(N\) times, the overall time complexity is \(O(N \log N)\).
  • Space Complexity: \(O(N)\)
    • The memory required for the coordinate compression array and the two segment trees is \(O(N)\).

Implementation Details

  • Handling the case of choosing nothing: Since the total score when choosing nothing is \(0\), this can be naturally handled by initializing the answer to \(0\).

  • Transitions for length 1 sequences: When choosing only one element, the next movement can be either an increase or a decrease, so this element should be registered in the segment trees as both a “peak” and a “valley”.

  • Care with overflow: The total score and the initial value of the segment trees (\(-\infty\)) can exceed the range of a 32-bit integer, so use a 64-bit integer type (long long). Using approximately \(-2 \times 10^{18}\) for \(-\infty\) is safe.

    Source Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <atcoder/segtree>

using namespace std;

const long long INF = 2e18;

long long op(long long a, long long b) {
    return std::max(a, b);
}

long long e() {
    return -INF;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    long long l_bound, r_bound;
    if (!(cin >> n >> l_bound >> r_bound)) return 0;

    vector<long long> a(n), b(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i] >> b[i];
    }

    vector<long long> coords = a;
    sort(coords.begin(), coords.end());
    coords.erase(unique(coords.begin(), coords.end()), coords.end());

    int m = coords.size();
    atcoder::segtree<long long, op, e> seg_up(m);
    atcoder::segtree<long long, op, e> seg_down(m);

    long long ans = 0;

    for (int i = 0; i < n; ++i) {
        long long dp_down = -INF;
        long long dp_up = -INF;

        // dp_down: 直前が減少 (A_j > A_i, A_j in [A_i + L, A_i + R])
        {
            long long ql = a[i] + l_bound;
            long long qr = a[i] + r_bound;
            int l = lower_bound(coords.begin(), coords.end(), ql) - coords.begin();
            int r = upper_bound(coords.begin(), coords.end(), qr) - coords.begin();
            if (l < r) {
                long long mx = seg_up.prod(l, r);
                if (mx > -INF / 2) {
                    dp_down = b[i] + mx;
                }
            }
        }

        // dp_up: 直前が増加 (A_j < A_i, A_j in [A_i - R, A_i - L])
        {
            long long ql = a[i] - r_bound;
            long long qr = a[i] - l_bound;
            int l = lower_bound(coords.begin(), coords.end(), ql) - coords.begin();
            int r = upper_bound(coords.begin(), coords.end(), qr) - coords.begin();
            if (l < r) {
                long long mx = seg_down.prod(l, r);
                if (mx > -INF / 2) {
                    dp_up = b[i] + mx;
                }
            }
        }

        long long from_down = max(b[i], dp_down);
        long long from_up = max(b[i], dp_up);

        ans = max({ans, from_down, from_up});

        int idx = lower_bound(coords.begin(), coords.end(), a[i]) - coords.begin();
        seg_up.set(idx, max(seg_up.get(idx), from_up));
        seg_down.set(idx, max(seg_down.get(idx), from_down));
    }

    cout << ans << "\n";

    return 0;
}

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

posted:
last update: