Technology Planning

Plan the smallest set of technologies covering every goal plus its dependencies, then print the lexicographically smallest valid research order.

Medium5Topological sortGraphHeapDFSInterviewNo attempts yetTime limit5sMemory limit512 MB

Problem

You are playing a culture simulation game in which your culture develops technologies. Some technologies depend on others. If technology A depends on technology B, you have to develop B before you can develop A. Your culture develops one technology at a time.

The game gives you goals that require particular technologies. Write a program that plans which technologies to develop, and in what order, so that every goal technology is reached.

Input

The first line holds the number of test cases, TT. Then TT test cases follow, each one in this form.

  • One line with an integer MM, the number of dependencies.
  • MM lines, each holding two technology names separated by a colon (:). The first technology depends on the second one.
  • One line with an integer QQ, the number of goal technologies.
  • QQ lines, each naming one goal technology.

A technology name is a string of letters and digits, and names are case sensitive. The same dependency or the same goal technology may be given more than once. A goal technology may appear in no dependency line at all.

Limits

  • 1T251 \le T \le 25
  • 1M1001 \le M \le 100
  • 1Q1001 \le Q \le 100
  • The dependency graph has no cycles.

Output

For each test case, first print a line of the form "Case #CC: DD", where CC is the test case number starting from 1 and DD is the smallest number of technologies that have to be researched. Then print DD lines, one technology name per line, in the order they are researched.

If several orders satisfy the dependencies, print only the lexicographically smallest one. Compare two orders line by line from the first line, and compare technology names by the ASCII value of their characters, so digits come before uppercase letters and uppercase letters come before lowercase letters.