Studschiffret
Time limit1sMemory limit1024 MB
Simulate a beam that travels diagonally through an N by M grid, bouncing off walls and skipping filled cells, to reconstruct the original plaintext from the row-by-row ciphertext.
- Level
Medium6 of 10
- Topics
- Simulation, Implementation, Matrix, Array
- Solved
- No attempts yet
Problem
Fretchif has invented a revolutionary cipher that nobody will be able to break! Here is how it works. You choose a string to encrypt and two integers and . Then you draw a grid with rows and columns. You then write the string you are encrypting one letter at a time diagonally down and to the right, starting from the top left corner. If we number the columns from left to right to , and the rows from top to bottom to , the first letter lands at position , the second at , the third at , and so on. When the "letter beam" reaches one of the grid's walls, it bounces off the wall (see the explanation in the hint). If it ever lands on a cell that already has a letter in it, the letter you were about to write is written in the next free cell you reach instead. Once all the letters of the string being encrypted are used up, you read the grid row by row, and that becomes the encrypted message.
Given a message that Fretchif encrypted with the studschiffret, and given the size of the grid that was used, print the original message.
Note that some messages cannot be encrypted with some grid sizes, since it is possible to never reach a new free cell while still having letters left to place. Here, however, it is guaranteed that this did not happen when Fretchif encrypted the string.
Input
The first line contains two integers and , the number of rows and columns in the grid. The second line contains a string of letters (), the encrypted message. The message consists only of the letters A to Z, and all letters are uppercase. It is guaranteed that there exists a possible original string that produces this ciphertext.
Output
The program shall print one line with a string: the original message, as it looked before it was encrypted.
Hint
Say the string we want to encrypt is ABCDEFGHIKLMNOPQRST, and the grid has size . Here is what the grid looks like at various points during the encryption:
In this example the encrypted message is therefore ATKBSJLCRIMDHNEGQOFP. Sample 2 is to decode ATKBSJLCRIMDHNEGQOFP, which decodes to ABCDEFGHIJKLMNOPQRST.



