Technology Planning
InterviewTime limit5sMemory limit512 MB
Find every goal technology plus its prerequisites and print the smallest valid research order, breaking ties lexicographically.
- Level
Medium5 of 10
- Topics
- Topological sort, Graph
- Solved
- No attempts yet
Problem
In a culture simulation game your culture develops technologies. Some technologies depend on others. If technology A depends on technology B, you can develop A only after B is developed. Your culture works on one technology at a time.
The game gives you goals that require particular technologies. Given the goal technologies, compute the smallest number of technologies you have to research and the order in which to research them.
Input
The first line holds the number of test cases, . test cases follow, each one shaped like this.
- One line with an integer , the number of dependencies.
- lines, each with two technology names separated by a colon (:). The first technology depends on the second one.
- One line with an integer , the number of goal technologies.
- lines, each naming one goal technology.
A technology name is a sequence of letters and digits. Names are case sensitive.
Limits
- The dependency graph has no cycles.
- The same dependency or the same goal technology can appear more than once.
- A goal technology can be absent from every dependency.
Output
For each test case, first print a line of the form Case #C: D, where is the test case number starting from 1 and is the smallest number of technologies that have to be researched. Then print lines, each holding one technology, in the order they are researched.
When several orders satisfy the rules, print only the lexicographically smallest one. To compare two orders, find the first position where the technology names differ and compare those names by Unicode code point, so digits come before uppercase letters and uppercase letters come before lowercase letters.