Official

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

gpt-6-astra-medium

Overview

Replace each character of the string \(S\) with the character that is \(K\) positions after it in alphabetical order. Wrap around so that A follows Z, and output the resulting string.

Analysis

There are \(26\) letters in the alphabet in total, so shifting by \(26\) positions returns to the original character. By utilizing this property, we can handle the wrap-around using the modulo operator %.

First, represent each character by an integer from \(0\) to \(25\) as follows:

  • A → \(0\)
  • B → \(1\)
  • \(\ldots\)
  • Z → \(25\)

Let \(x\) be the number representing the original character. Then the number after shifting is

\((x + K) \bmod 26\)

where \(\bmod 26\) represents the remainder when divided by \(26\).

For example, when shifting Y by \(3\) positions, since the number for Y is \(24\):

\((24 + 3) \bmod 26 = 1\)

which gives us B corresponding to the number \(1\).

A method that shifts each character one position at a time \(K\) times would also easily run within the time limit under these constraints. However, simply adding \(K\) to the character code will result in a character that is no longer an uppercase English letter once it goes past Z, leading to a Wrong Answer. Furthermore, since \(K\) can be \(26\) or greater, subtracting \(26\) just once is not sufficient. Using the modulo operation allows us to convert correctly no matter how many full cycles are made.

Algorithm

  1. Read \(K\) and \(S\).
  2. For each character c in \(S\), perform the following:
    1. Convert the character to a number from \(0\) to \(25\) using ord(c) - ord('A').
    2. Add \(K\) to the number and compute the remainder modulo \(26\).
    3. Add ord('A') back and use chr to convert it back to an uppercase English letter.
  3. Concatenate the converted characters in order and output the result.

For example, if \(K = 3\) and \(S = \text{XYZ}\), the characters are converted as X → A, Y → B, and Z → C, so we output ABC.

Complexity

Let \(N = |S|\).

  • Time Complexity: \(O(N)\)
    Each character is converted once.
  • Space Complexity: \(O(N)\)
    Required to construct the resulting string.

Implementation Details

  • ord(c) returns the character code of character c, and chr(x) returns the character corresponding to character code x.

  • % 26 should be applied after converting the character to a number where A corresponds to \(0\).

  • Using "".join(...) allows you to concatenate the converted characters without any delimiter.

  • Even when \(K = 0\) or \(K\) is a multiple of \(26\), the same formula correctly yields the original string.

    Source Code

# 問題文から独立に実装: 各文字を 0〜25 の番号に直して K を足し、26 で割った余りを戻す
k = int(input())
s = input().strip()
print("".join(chr((ord(c) - ord('A') + k) % 26 + ord('A')) for c in s))

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

posted:
last update: