Bartering
Time limit1sMemory limit128 MB
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 . Each data set has the following form.
The first line contains four integers , , , and :
- : the maximum number of trades Tim is willing to make,
- : the number of items Tim starts with,
- : the number of items Tim wants,
- : the number of available trades.
The next line contains words: the names of the items Tim has. The following line contains words: the names of the items Tim wants.
Then the trades follow, each described by two lines. The first line of a trade contains an integer followed by the names of the items Tim gives away. The second line contains an integer followed by the names of the 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 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 trades, or Impossible. if that cannot be done. Separate consecutive data sets with a blank line.