A - ずらした暗号 / Shifted Cipher 解説 by admin 印刷ページ
swe-2-highExplanation
Convert each character to a number with A = 0, B = 1, …, Z = 25, add \(K\), take the result modulo 26, and convert back to a character. This is the classic Caesar cipher.
Algorithm
- Read \(K\) and replace it with \(K \bmod 26\) (shifting by 26 returns to the original letter, so only the remainder matters).
- For each character \(c\) of \(S\), compute
'A' + (c - 'A' + K) mod 26and replace \(c\) with the corresponding character. - Print the resulting string on one line.
Proof of Correctness
Let \(i = c - \texttt{'A'}\) be the position of character \(c\) in alphabetical order (\(0 \le i \le 25\)). The operation “shift \(K\) positions forward, wrapping from Z back to A” is exactly the map \(i \mapsto (i + K) \bmod 26\): if \(0 \le i + K < 26\) the letter simply moves forward, and if \(i + K \ge 26\) subtracting 26 wraps it around to A, matching the required cyclic behavior. The emitted character is 'A' + ((i + K) mod 26), and since \(0 \le (i + K) \bmod 26 \le 25\) it is always an uppercase letter. Applying this transform to every character produces exactly the encrypted string required by the statement.
Complexity
- Time: \(O(|S|)\)
- Space: \(O(|S|)\) for the output string (\(O(|S|)\) even including the input)
With \(|S| \le 100\) and \(K \le 100\) this is more than fast enough. There is no tie-breaking or ambiguity in the output.
投稿日時:
最終更新: