Anagram Pyramids (Hard)

Given a dictionary and query word pairs, decide whether an anagram pyramid can be built from the top word down to the bottom word.

Medium6GraphDFSString matchingNo attempts yetTime limit10sMemory limit512 MB

Problem

In the 20th century, anagram puzzles ran on the back pages of newspapers. They never became as popular as sudoku, but they were a dependable way to spend a few minutes. One variant is the anagram pyramid, a stack of words in which the bottom word has NN letters, the word above it has N1N-1 letters, the next one has N2N-2 letters, and so on. Every word except the bottom one is formed by deleting one letter from the word directly below it and shuffling the rest. Here is one anagram pyramid, listed from the top down.

  • PIN
  • SNIP
  • PAINS
  • PIANOS

Zino Ponzi, a retired financier, was thinking back on old times when he decided to build a few anagram puzzles for his friends at the Zigurat Retirement Home. He wanted to keep the fun of constructing the pyramids by hand, but he kept getting stuck on a word somewhere in the middle, so he hired a computer science student to write a program. The program only has to report whether an anagram pyramid is possible for a given dictionary, top word, and bottom word.

Every word used in a pyramid must appear in the dictionary. Given a top word and a bottom word, decide whether an anagram pyramid exists with the bottom word at the base and the top word at the apex. Upper and lower case versions of the same letter count as equal.

Input

The input holds several test cases. Process cases until the end of the file.

Each test case starts with the dictionary size NN (N<106N < 10^6) followed by NN words. After that come the number of queries MM (M<100M < 100) and MM word pairs. Each pair gives the top word first and the bottom word second. Both words of a pair appear in the dictionary, and the top word is shorter than the bottom word.

Every word is a string of 1 to 30 letters. Case does not matter.

The tokens appear in this order.

N
word1
...
wordN
M
top1 bottom1
...
topM bottomM

Do not assume the line breaks match that layout. Any whitespace character separates tokens, so read the input token by token.

Output

For each test case, first print a line made of Case, one space, the case number, and a colon. Case numbers start at 1 and grow by 1 in input order.

Then print one line per query: yes if an anagram pyramid is possible for that pair, no if it is not. Keep the queries in input order.

Do not leave trailing spaces on a line, and do not print a blank line between cases.