Anagram Pyramids
Time limit2sMemory limit256 MB
Decide whether dictionary words can link the base word to the apex word by deleting and rearranging one letter at each step.
Problem
Anagram puzzles filled the back pages of newspapers in the 20th century. One of them is the anagram pyramid, a stack of words. The word at the base has letters, the word above it has letters, the next one has letters, and so on. Every word except the one at the base is formed by removing one letter from the word below it and rearranging the remaining letters.
Here is one anagram pyramid:
- PIN
- SNIP
- PAINS
- PIANOS
You are given a dictionary and two words, one for the apex and one for the base. Write a program that decides whether an anagram pyramid can be stacked with the base word at the bottom and the apex word at the top. Every word in the pyramid has to come from the dictionary.
Input
The input holds several test cases. Process it until the end of the file.
The first line of each test case has , the number of words in the dictionary (). Each of the next lines has one word. The line after those has , the number of queries (). Each of the next lines has the apex word and the base word separated by one space. Both words are in the dictionary, and the apex word is shorter than the base word.
Every word is 1 to 30 letters long. The upper case and lower case forms of a letter count as the same letter.
Output
For each test case, print Case, one space, the case number, and a colon on one line. Case numbers start at 1 and run over the whole input. Then print one line per query, in input order: yes if the pyramid can be stacked, no if it cannot.
Print no trailing space on any line, and no blank line between test cases.