This page is still under construction.

Parts of this page are still being built. What you see may change.

Bartering

Time limit1sMemory limit128 MB

Summary
Given starting items, wanted items, and up to 20 barter trades usable at most M times, find the fewest trades to hold all wanted items while never exceeding 5 held items.
Level

Medium7 of 10

Topics
BFS, Graph, Bit manipulation, Brute force
Solved
No attempts yet

Problem

Tim has discovered that, at a certain point in the future, medieval artifacts — especially the weapons and armor of the era's armies — become extremely valuable. He plans to travel back to the Middle Ages, gather items such as chainmail and lances, and later sell them for a fortune.

The catch is that he has no currency the locals will accept, so he must obtain everything he needs by bartering. Before he starts trading, Tim wants to know the fewest trades each item will cost him, so he can focus first on the items that take the fewest trades.

His time machine can hold at most 5 items at once, and Tim will never make a trade that leaves him holding more than 5 items.

Input

The first line contains the number of data sets KK. Each data set has the following form.

The first line contains four integers MM, HH, WW, and TT:

  • 1≤M≤201 \le M \le 20: the maximum number of trades Tim is willing to make,
  • 1≤H≤51 \le H \le 5: the number of items Tim starts with,
  • 1≤W≤51 \le W \le 5: the number of items Tim wants,
  • 1≤T≤201 \le T \le 20: the number of available trades.

The next line contains HH words: the names of the items Tim has. The following line contains WW words: the names of the items Tim wants.

Then the TT trades follow, each described by two lines. The first line of a trade contains an integer 1≤g≤51 \le g \le 5 followed by the names of the gg items Tim gives away. The second line contains an integer 1≤a≤51 \le a \le 5 followed by the names of the aa items Tim receives.

To perform a trade, Tim must currently hold every item it requires him to give away, and after the trade the total number of items he holds must not exceed 5.

Output

For each data set, print a line Data Set x:, where xx is the data set's number (starting from 1). On the next line, print the fewest number of trades Tim needs to obtain every wanted item using at most MM trades, or Impossible. if that cannot be done. Separate consecutive data sets with a blank line.

Examples2

  1. Example 1

    Input
    2
    4 3 2 3
    coin butterknife suit
    sword chainmail
    1 suit
    1 chainmail
    3 butterknife butterknife butterknife
    1 sword
    1 coin
    2 butterknife butterknife
    1 1 1 2
    pvcpipe
    lance
    1 pvcpipe
    1 shield
    1 shield
    1 lance
    
    Expected output
    Data Set 1:
    3
    
    Data Set 2:
    Impossible.
    
  2. Example 2

    Input
    1
    1 1 1 1
    wood
    chair
    1 wood
    1 chair
    
    Expected output
    Data Set 1:
    1