Open all N chests in the lexicographically smallest order with single-use typed keys taken from other chests, or report IMPOSSIBLE.
Medium7GreedyGraphBacktrackingNo attempts yetTime limit5sMemory limit512 MBAn old map led you to the pirate Larry's hidden treasure vault.
The vault holds N 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.
| Chest | Key type that opens it | Key types inside |
|---|---|---|
| 1 | 1 | none |
| 2 | 1 | 1, 3 |
| 3 | 2 | none |
| 4 | 3 | 2 |
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.
The first line has the number of test cases T. T test cases follow.
Each test case begins with a line holding two positive integers K and N: the number of keys you start with and the number of chests you must open.
The next line holds K integers, the types of the keys you start with.
Then come N lines. Line i describes chest i and begins with two integers ti and mi: the key type needed to open that chest and the number of keys inside it. Those are followed by mi integers, the types of the keys inside the chest.
The limits are as follows.
For each test case, print one line in the form Case #x: C1 C2 ... CN, where x is the test case number starting from 1 and Ci is the index of the i-th chest you open. Chest indices start from 1.
If several orders open every chest, print the lexicographically smallest one: make C1 as small as possible, then among the orders that do so make C2 as small as possible, and so on.
If no order opens every chest, print Case #x: IMPOSSIBLE on that line instead.