Programming contests

ACM ICPC programozó csapatverseny, házi forduló, 2016. október 15.

October 15, 2016 10:00 AM – October 15, 2016 3:00 PM

What's on the Grille?

The grille cipher is a technique that dates back to 1550, when it was first described by Girolamo Cardano. The version we'll be dealing with comes from the late 1800's and works as follows. The message to be encoded is written on an n × n grid row-wise, top to bottom, and is overlaid with a card with a set of holes punched out of it (this is the grille).

The message is encrypted by writing down the letters that appear in the holes, row by row, then rotating the grille 90 degrees clockwise, writing the new letters that appear, and repeating this process two more times. Of course, the holes in the grille must be chosen so that every letter in the message will eventually appear in a hole (this is actually not that hard to arrange).

An example is shown below, where the message “Send more monkeys” is encrypted as “noeesrksdmnyemoj”, after adding a random letter to fill out the grid (this example corresponds to the first sample input).

If the message is larger than the n × n grid, then the first n2 letters are written in the grid and encrypted, then the next n2 are encrypted, and so on, always filling the last grid with random letters if needed. Here, we will only be dealing with messages of length n2.

Your job, should you choose to accept it, is to take an encrypted message and the corresponding grille and decrypt it. And we'll add one additional twist: the grille given might be invalid, i.e., the holes used do not allow every location in the grid to be used during the encryption process. If this is the case, then you must indicate that you can't decrypt the message.

Input Specification

The input contains several test cases. Each test case starts with a line containing a positive integer n ≤ 10, indicating the size of the grid and grille. The next n lines will specify the grille, using '.' for a hole and 'X' for a nonhole. Following this will be a line containing the encrypted message, consisting solely of lowercase alphabetic characters. The number of characters in this line will always be n2.

Output Specification

For each test case, output the decrypted text as a single string with no spaces, or the phrase “invalid grille” if the grille is invalid.

Sample Input

  1. 4
  2. XX.X
  3. X.X.
  4. XXXX
  5. .XXX
  6. noeesrksdmnyemoj
  7. 4
  8. .XX.
  9. XXXX
  10. XXXX
  11. .XX.
  12. abcdefghijklmnop
  13. 2
  14. X.
  15. XX
  16. aybb
download as text file

Output for Sample Input

  1. sendmoremonkeysj
  2. invalid grille
  3. baby
download as text file
University of Debrecen; Faculty of Informatics; v. 03/01/2019