#P10312. Rail Fence Cipher Decryption
Rail Fence Cipher Decryption
Rail Fence Cipher Decryption
The rail fence cipher is a basic transposition cipher. In this cipher, the plaintext is written in a zigzag pattern on a number of rows (rails) and then read row by row to produce the ciphertext. For example, if we take the plaintext Hello,World!
and write it in a rail fence of height h = 3, we arrange the characters as follows:
H o r e l , o l ! l W d
The ciphertext is obtained by reading each row from left to right: first row gives Hor
, second gives el,ol!
and third gives lWd
. Hence, the final ciphertext is Horel,ol!lWd
.
In general, if the ciphertext formed by writing in a rail fence of height h is given, we can retrieve the original plaintext by reconstructing the zigzag pattern. The indices follow a pattern that can be formally described by the formula: \[ pattern(i)=\begin{cases} i\quad,&\text{if } h=1,\\ \text{zigzag } 0\to h-1 \text{ and back},&\text{if } h>1. \end{cases} \]
Your task is: Given the height h and a ciphertext string s
(encrypted as described above), output the original plaintext string.
inputFormat
The input consists of two lines:
- The first line contains an integer
h
representing the height of the rail fence. - The second line contains a non-empty string
s
which is the ciphertext.
outputFormat
Output a single line: the decrypted plaintext string.
sample
3
Horel,ol!lWd
Hello,World!