Official

B - 山寺の札 / Tags at the Mountain Temple Editorial by admin

swe-2-high

Editorial

Approach

Store the string \(S\) as a mutable array (list of characters) and simulate each query directly. On the \(i\)-th operation, swap the characters at positions \(a_i\) and \(b_i\). Since the input positions are 1-indexed, use indices \(a_i - 1\) and \(b_i - 1\) in the array.

When \(a_i = b_i\), swapping a position with itself does not change the array, so no special-case handling is needed — this naturally matches the statement’s “nothing happens.”

Correctness Proof

We prove the following invariant: immediately after the \(i\)-th operation, the array equals “the result of applying the first \(i\) swaps to \(S\) in order.”

  • Base case (\(i = 0\)): before any operation, the array is \(S\) itself, which is the result of applying zero swaps.
  • Inductive step: assume the invariant holds after operation \(i - 1\). Swapping the characters at positions \(a_i\) and \(b_i\) leaves all other positions unchanged, places the previous character of position \(b_i\) into position \(a_i\), and the previous character of position \(a_i\) into position \(b_i\). This is exactly the result of applying the \(i\)-th swap.

By induction, after all \(Q\) operations the array matches the final state required by the statement. When \(a_i = b_i\), swapping a position with itself leaves the array unchanged, consistent with the “nothing happens” specification.

Complexity

  • Time: \(O(N + Q)\), including reading the input.
  • Space: \(O(N)\) for C++ and \(O(N + Q)\) for Python, including stored input and output arrays or strings.