Official

A - ずらした暗号 / Shifted Cipher Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

We convert each character of the string \(S\) to the character that is \(K\) positions ahead in alphabetical order. We simulate the operation of advancing one character at a time, wrapping around from Z to A.

Analysis

Since converting each character does not affect the other characters, we can process the string sequentially from beginning to end.

The operation of “advancing one character ahead” is performed as follows:

  • If the current character is Z, change it to A.
  • Otherwise, increment the character code by \(1\) to change it to the next character.

For example, shifting Y by \(3\) positions proceeds as follows:

Y → Z → A → B

Simply adding \(K\) to the character code will not wrap around to A when exceeding Z, resulting in an incorrect answer. Therefore, we check whether the character is Z each time we advance by one.

Under the given constraints, both the length of the string and \(K\) are at most \(100\). Even if we perform the operation \(K\) times for each character, the total number of operations is at most \(100 \times 100 = 10{,}000\), so this naive approach is well within the time limit.

Algorithm

  1. Read \(K\) and the string \(S\).
  2. For each character in \(S\), repeat the following operation \(K\) times:
    • If it is Z, replace it with A.
    • Otherwise, replace it with the next character in alphabetical order.
  3. Print the transformed \(S\).

Since each operation correctly advances the character by one, repeating this \(K\) times shifts each character by exactly \(K\) positions. Therefore, the string obtained after processing all characters is the desired cipher.

Complexity

Let \(N = |S|\).

  • Time complexity: \(O(N(K+1))\)
    • We perform \(K\) transformations for each character. This notation is used because scanning and outputting the string still occur even when \(K=0\).
  • Space complexity: \(O(N)\)
    • Required to store the input string. Since we modify the string in place, the additional working space is \(O(1)\).

Implementation Notes

  • In the provided code, for (char& c : s) accesses each character by reference. Modifying c will directly modify the corresponding character in the string s.

  • Only when the character is Z, we assign A instead of incrementing its character code.

  • When \(K=0\), the inner loop is never executed, and the original string is output as is.

  • Even if \(K\) is \(26\) or greater, repeatedly cycling from Z to A will handle it correctly.

    Source Code

// 問題文から独立に実装: 1文字ずつ K 回「次の文字」に進める(Z の次は A)
#include <iostream>
#include <string>
int main() {
    int k; std::string s;
    std::cin >> k >> s;
    for (char& c : s) {
        for (int step = 0; step < k; ++step) {
            if (c == 'Z') c = 'A'; else c = c + 1;
        }
    }
    std::cout << s << std::endl;
}

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

posted:
last update: