J - コマの移動 / Moving the Piece Editorial by admin Editorial for printing
Gemini 3.8 Flash (High)Overview
This is a simulation problem where obstacles are added one by one on a number line, and whenever an obstacle is placed at the same position as the piece, the piece is moved to the nearest unoccupied cell (breaking ties by choosing the larger coordinate).
By managing contiguous intervals of obstacles using Union-Find (Disjoint Set Union), we can quickly determine the destination of the piece.
Analysis
Naive Approach and Its Issues
When an obstacle is placed at the piece’s current coordinate, the first approach that comes to mind is to search left and right one step at a time from that position to find the first cell without an obstacle.
However, if there is a long contiguous sequence of obstacles, scanning through them to find an empty cell takes \(O(N)\) time per move in the worst case. Since there are \(N\) events, the overall time complexity would be \(O(N^2)\), which exceeds the time limit (resulting in TLE). Furthermore, because coordinates can reach up to \(10^9\), we cannot manage obstacles using a standard array.
Key Insight
The piece moves only when “an obstacle is placed on its current cell.”
Let \([L, R]\) be the contiguous interval of obstacles containing the cell \(X_i\) where the piece is located. Since the entire interior of this interval (all integer coordinates from \(L\) to \(R\)) is filled with obstacles, the only candidate empty cells are immediately outside the interval: either \(L - 1\) or \(R + 1\).
- Distance to the empty cell on the right, \(R + 1\): \((R + 1) - X_i\)
- Distance to the empty cell on the left, \(L - 1\): \(X_i - (L - 1)\)
By comparing these two distances: - If distance to the right \(\leq\) distance to the left, move to \(R + 1\) (the \(\leq\) handles the tie-breaking rule of choosing the larger coordinate) - Otherwise, move to \(L - 1\)
Thus, we can determine the destination in \(O(1)\) time as long as we know the interval \([L, R]\).
Managing Intervals
When an obstacle is placed, if adjacent cells (\(X_i - 1\) or \(X_i + 1\)) already contain obstacles, they merge into a single contiguous interval. Such operations of “merging adjacent elements” can be handled very efficiently using Union-Find.
Algorithm
Setting up Union-Find Since coordinates can be negative or very large, instead of an array, we build a Union-Find data structure where nodes are managed dynamically using an associative array (such as a dictionary in Python). Each group’s representative (root) maintains the following information:
min_val: The minimum coordinate of the group (left endpoint \(L\) of the interval)max_val: The maximum coordinate of the group (right endpoint \(R\) of the interval) Update these values whenever two groups are merged.
Processing Events Let \(\text{pos} = 0\) be the initial coordinate of the piece. For each \(X_i\), perform the following:
- If an obstacle already exists at \(X_i\), do nothing.
- Register \(X_i\) as a new obstacle (initial state: \(L = X_i, R = X_i\)).
- If there is already an obstacle at \(X_i - 1\), merge with the group containing \(X_i - 1\).
- If there is already an obstacle at \(X_i + 1\), merge with the group containing \(X_i + 1\).
- If \(\text{pos} == X_i\):
- Find the root of the group that \(X_i\) belongs to and retrieve the interval \([L, R]\).
- Compare the distance to the right \((R + 1 - X_i)\) and the distance to the left \((X_i - (L - 1))\), and update \(\text{pos}\) to the closer one (or the right one in case of a tie).
Output Print \(\text{pos}\) after processing all events.
Complexity
- Time Complexity: \(O(N \alpha(N))\) (expected)
- For \(N\) obstacles, dictionary access takes \(O(1)\) expected time, and Union-Find’s
findandunionoperations take amortized \(O(\alpha(N))\) time (where \(\alpha\) is the inverse Ackermann function, practically a constant \(\le 4\)). - Overall, this easily runs well within the time limit.
- For \(N\) obstacles, dictionary access takes \(O(1)\) expected time, and Union-Find’s
- Space Complexity: \(O(N)\)
- Storing at most \(N\) obstacle nodes along with their parents, sizes, and minimum/maximum values in dictionaries takes \(O(N)\) space.
Implementation Notes
Avoiding Recursion: In Python, deep recursion may cause a
RecursionError, so it is safer to implement the Union-Findfindoperation iteratively with path compression.Ignoring Duplicate Inputs: Since obstacles may be placed at the same coordinate multiple times (i.e., duplicate \(X_i\)), skip processing for coordinates that already have an obstacle.
Source Code
import sys
def main():
input_data = sys.stdin.read().split()
if not input_data:
return
N = int(input_data[0])
X = [int(x) for x in input_data[1 : N + 1]]
parent = {}
size = {}
min_val = {}
max_val = {}
def find(i):
path = []
curr = i
p = parent[curr]
while p != curr:
path.append(curr)
curr = p
p = parent[curr]
for node in path:
parent[node] = curr
return curr
def union(i, j):
root_i = find(i)
root_j = find(j)
if root_i != root_j:
if size[root_i] < size[root_j]:
root_i, root_j = root_j, root_i
parent[root_j] = root_i
size[root_i] += size[root_j]
if min_val[root_j] < min_val[root_i]:
min_val[root_i] = min_val[root_j]
if max_val[root_j] > max_val[root_i]:
max_val[root_i] = max_val[root_j]
pos = 0
for x in X:
if x in parent:
continue
parent[x] = x
size[x] = 1
min_val[x] = x
max_val[x] = x
if x - 1 in parent:
union(x - 1, x)
if x + 1 in parent:
union(x, x + 1)
if pos == x:
r = find(x)
L = min_val[r]
R = max_val[r]
d_right = R + 1 - x
d_left = x - (L - 1)
if d_right <= d_left:
pos = R + 1
else:
pos = L - 1
print(pos)
if __name__ == "__main__":
main()
This editorial was generated by gemini-3.8-flash-high.
posted:
last update: