Official

J - コマの移動 / Moving the Piece Editorial by admin Editorial for printing

Gemini 3.8 Flash (High)

Overview

This is a simulation problem where obstacles are sequentially added to a number line, and whenever an obstacle is placed at the current position of a piece, the piece is evacuated to the “nearest empty cell (or in the positive direction in case of a tie).” We can efficiently process each event by managing contiguous intervals of obstacles.

Analysis

Naive Approach and Its Issues

When an obstacle is placed at the piece’s position, the first method that comes to mind is to search from the piece’s current position \(X_i\) in the order of \(+1, -1, +2, -2, \dots\) to check whether an obstacle is already present. However, if there is a long contiguous segment of obstacles (for example, arranged at \(1, 2, \dots, K\)), it takes \(O(K)\) search steps to find an empty cell. In the worst case, an \(O(N)\) search occurs for each event, resulting in an overall time complexity of \(O(N^2)\), which will exceed the time limit (TLE).

Managing Obstacles as “Intervals”

Here is an important observation: The piece only needs to move “when an obstacle is placed at the coordinate \(X_i\) where the piece is currently located.”

At this point, let \([L, R]\) be the maximal contiguous interval of obstacles containing \(X_i\) on the number line after the obstacle is placed. Because it is maximal, there are never any obstacles at \(L - 1\) and \(R + 1\), which are immediately outside the endpoints of the interval.

Therefore, there are only \(2\) candidates for the nearest empty cell from the piece’s current position \(X_i\): 1. Nearest empty cell to the left: \(L - 1\) (distance is \(X_i - (L - 1)\)) 2. Nearest empty cell to the right: \(R + 1\) (distance is \((R + 1) - X_i\))

By comparing these distances, we can see that the piece should move to the closer one (or to the right side \(R + 1\) if the distances are equal). In other words, if we can quickly query and update the “contiguous obstacle intervals \([L, R]\)”, we can solve this problem efficiently.

Algorithm

To manage contiguous intervals of obstacles, we use a balanced binary search tree (such as std::set in C++), a technique often referred to as the interval set technique.

We store each interval \([l, r]\) in a set as a pair<long long, long long>, sorted in ascending order of \(l\).

For each query \(X_i\), perform the following steps:

  1. Binary Search: Identify the intervals immediately before and after \(X_i\) using intervals.upper_bound({X_i, ...}).
  2. Interval Update:
    • If \(X_i\) is already contained in some interval \([L, R]\): Do nothing (an obstacle already exists there).
    • If \(X_i\) is not contained in any interval:
      • If the preceding interval ends at \(X_i - 1\), merge with it.
      • If the succeeding interval starts at \(X_i + 1\), merge with it as well.
      • Erase the old interval(s) from the set and insert the newly extended interval \([L, R]\) into the set.
  3. Piece Movement Check:
    • If the current position of the piece coincides with \(X_i\):
      • Distance to the left empty cell: \(d_L = X_i - (L - 1)\)
      • Distance to the right empty cell: \(d_R = (R + 1) - X_i\)
      • If \(d_R \leq d_L\), move the piece to \(R + 1\); otherwise, move it to \(L - 1\).

Complexity

  • Time Complexity: \(O(N \log N)\) In each query, we perform search, insertion, and deletion operations on the set. The total number of inserted intervals is at most \(N\), and the total number of deleted intervals is also at most \(N\) (amortized), so all operations complete in \(O(N \log N)\) overall.
  • Space Complexity: \(O(N)\) Since the number of intervals stored in the set is at most \(N\), the space complexity is \(O(N)\).

Implementation Details

  • Use of 64-bit Integers: Coordinates \(X_i\) can be up to \(\pm 10^9\), and moving the piece may cause it to slightly exceed the range of \(\pm 10^9\). Therefore, use the long long type for coordinate and distance calculations.

  • Tie-Breaking Rule: Because of the rule “if the distances are equal, choose the one with the larger value,” we must prioritize the right side by using d_R <= d_L (with equality).

  • Merging Intervals: When obtaining the elements immediately before and after using upper_bound, it is crucial to perform proper bounds checks to ensure the iterator does not point to begin() or end().

    Source Code

#include <iostream>
#include <set>
#include <climits>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    if (!(cin >> n)) return 0;

    set<pair<long long, long long>> intervals;
    long long pos = 0;

    for (int i = 0; i < n; ++i) {
        long long x;
        cin >> x;

        long long L = x, R = x;
        auto it = intervals.upper_bound({x, LLONG_MAX});

        if (it != intervals.begin()) {
            auto pit = prev(it);
            if (pit->second >= x) {
                L = pit->first;
                R = pit->second;
                goto CHECK_MOVE;
            }
            if (pit->second == x - 1) {
                L = pit->first;
                intervals.erase(pit);
            }
        }

        if (it != intervals.end()) {
            if (it->first == x + 1) {
                R = it->second;
                intervals.erase(it);
            }
        }

        intervals.insert({L, R});

    CHECK_MOVE:
        if (pos == x) {
            long long d_R = (R + 1) - x;
            long long d_L = x - (L - 1);
            if (d_R <= d_L) {
                pos = R + 1;
            } else {
                pos = L - 1;
            }
        }
    }

    cout << pos << "\n";

    return 0;
}

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

posted:
last update: