公式

B - 山寺の札 / Tags at the Mountain Temple 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

Swap the characters at the \(2\) specified positions in the string in the order they are given in the input. The problem asks you to output the string after all operations have been completed.

Analysis

This problem can be solved by directly simulating each operation, maintaining the string itself as the current arrangement of cards.

Since \(1\) swap modifies only \(2\) characters, it can be processed in \(O(1)\) time. Therefore, naively performing all operations will easily finish in time.

However, simply performing assignments like the following will not swap them correctly:

s[a - 1] = s[b - 1];
s[b - 1] = s[a - 1];

This is because the first assignment overwrites and loses the character originally located at s[a - 1]. To prevent this, store one of the characters in a temporary variable before swapping.

For example, to swap the \(2\)-nd and \(4\)-th characters of abcde:

  1. Store the \(2\)-nd character b in a temporary variable.
  2. Overwrite the \(2\)-nd character with the \(4\)-th character d.
  3. Overwrite the \(4\)-th character with the stored b.

The result is adcbe. Subsequent operations are also performed on this updated string.

Algorithm

  1. Read \(N, Q, S\).
  2. Repeat the following \(Q\) times:
    • Read the positions \(a, b\) to swap.
    • Store S[a - 1] in a temporary variable tmp.
    • Assign S[b - 1] to S[a - 1].
    • Assign tmp to S[b - 1].
  3. Output the final string \(S\).

In each operation, only the characters at the \(2\) specified positions are correctly swapped. Since this is done in the input order, the final string will match the card arrangement required by the problem.

Complexity

  • Time Complexity: \(O(N + Q)\)
    • Reading and printing the string takes \(O(N)\), and the \(Q\) swaps take \(O(Q)\).
  • Space Complexity: \(O(N)\)
    • Stores a string of length \(N\). The additional memory required besides the string is \(O(1)\).

Implementation Notes

  • Positions in the problem statement are \(1\)-indexed, but string indices in C++ are \(0\)-indexed. Access positions \(a, b\) using s[a - 1] and s[b - 1], respectively.

  • The temporary variable tmp should be of type char because it stores \(1\) character.

  • Even when \(a = b\), it simply writes the original character back to the same position, so no special conditional branching is required.

  • Each operation is performed on the arrangement at that point in time. Be sure to process them in the order they are inputted.

    Source Code

// 問題文から独立に実装: 一時変数で3ステップ入れ替え
#include <iostream>
#include <string>
int main() {
    int n, q; std::string s;
    std::cin >> n >> q >> s;
    while (q--) {
        int a, b; std::cin >> a >> b;
        char tmp = s[a - 1];
        s[a - 1] = s[b - 1];
        s[b - 1] = tmp;
    }
    std::cout << s << std::endl;
}

This editorial was generated by gpt-6-astra-medium.

投稿日時:
最終更新: