Substitution Cipher Key
InterviewTime limit1sMemory limit64 MB
Given N distinct words and a target permutation, find the lexicographically smallest substitution cipher key that sorts the encrypted words into that order, or report none.
- Level
Hard8 of 10
- Topics
- Greedy, Sorting, String, Implementation
- Solved
- No attempts yet
Problem
Mirko has distinct words and wants to encrypt them with a substitution cipher.
A substitution cipher needs a key, a string that uses each of the 26 lowercase English letters exactly once. Encrypting replaces every 'a' in a word with the first letter of the key, every 'b' with the second letter of the key, and so on through 'z'.
Mirko also has an array , a permutation that holds each of the numbers to exactly once. He wants a key such that, after all words are encrypted and then sorted lexicographically, the word that started in position ends up in position .
Lexicographic order is the order in which words appear in a dictionary. To compare two words, scan them from left to right, find the first position where the letters differ, and call the word with the smaller letter there the smaller word. If word matches the beginning of word , then is smaller than .
Mirko is not in the mood for encrypting today, so find the key for him.
Input
The first line contains the integer . ()
Each of the next lines contains one word. A word consists of lowercase English letters only and has length at most . The words are all distinct.
The last line contains the elements of the array .
Output
If no key satisfies the requirement, print NE.
If a key exists, print DA on the first line and the key on the second line. The key is a string in which each of the 26 lowercase English letters appears exactly once. If several keys satisfy the requirement, print the lexicographically smallest one.
Hint
In the first example the two words become ba and ac after encryption. Sorting them lexicographically gives ac, ba, so the first word moves to the second position and the second word moves to the first position.