Opening the Treasure Chests
Time limit5sMemory limit512 MB
Open all N chests in the lexicographically smallest order with single-use typed keys taken from other chests, or report IMPOSSIBLE.
- Level
Medium7 of 10
- Topics
- Greedy, Graph, Backtracking
- Solved
- No attempts yet
Problem
An old map led you to the pirate Larry's hidden treasure vault.
The vault holds locked chests, and each chest opens only with a key of one particular type. A key disappears once it is used, so no key opens two chests. Every chest holds treasure, and some chests also hold keys to other chests. One chest may hold several keys of the same type, and you may carry any number of keys.
You start with at least one key, and the map records which keys sit inside which chest. Work out an order that opens every chest.
Suppose the vault holds four chests and you start with exactly one key of type 1.
Opening the chests in the order 2, 1, 4, 3 opens all four. Opening chest 1 first spends your only key and leaves you stuck.
Input
The first line has the number of test cases . test cases follow.
Each test case begins with a line holding two positive integers and : the number of keys you start with and the number of chests you must open.
The next line holds integers, the types of the keys you start with.
Then come lines. Line describes chest and begins with two integers and : the key type needed to open that chest and the number of keys inside it. Those are followed by integers, the types of the keys inside the chest.
The limits are as follows.
- Every key type is an integer between and .
- One test case holds at most 400 keys in total, counting the starting keys and the keys inside chests.
Output
For each test case, print one line in the form Case #x: C1 C2 ... CN, where is the test case number starting from 1 and is the index of the -th chest you open. Chest indices start from 1.
If several orders open every chest, print the lexicographically smallest one: make as small as possible, then among the orders that do so make as small as possible, and so on.
If no order opens every chest, print Case #x: IMPOSSIBLE on that line instead.