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.
Hard8GreedySortingStringImplementationInterviewNo attempts yetTime limit1sMemory limit64 MBMirko has N 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, a permutation that holds each of the numbers 1 to N exactly once. He wants a key such that, after all N words are encrypted and then sorted lexicographically, the word that started in position Ai ends up in position i.
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 X matches the beginning of word Y, then X is smaller than Y.
Mirko is not in the mood for encrypting today, so find the key for him.
The first line contains the integer N. (2≤N≤100)
Each of the next N lines contains one word. A word consists of lowercase English letters only and has length at most 100. The words are all distinct.
The last line contains the N elements of the array A.
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.
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.