Jack of All Trades
Time limit1sMemory limit128 MB
Given directed trades between items, find the minimum exchange ratio from one item to another using at most 9 trades, and count the chains achieving it.
- Level
Medium6 of 10
- Topics
- Graph, DFS, Shortest path
- Solved
- No attempts yet
Problem
Jack loves to barter: he will trade anything for anything as long as he comes out ahead. Right now he wants to acquire one kind of item and is willing to pay in another kind of item, possibly through a chain of intermediate trades with his friends.
Each friend offers a one-directional trade: a fixed amount of one item in exchange for a fixed amount of another item. A friend willing to give units of name1 in exchange for units of name2 does not necessarily make the reverse trade.
To keep things manageable, Jack never involves more than other people in a single chain of transactions, so a chain consists of at most trades.
The exchange ratio of a chain is the number of units of the item Jack is willing to trade that he must give up in order to obtain one unit of the item he wants. Among all chains that convert the item Jack is willing to trade into the item he wants, find the best (smallest) achievable ratio, and the number of distinct chains that achieve exactly that ratio.
Input
The first line contains an integer , the number of test cases.
Each test case begins with a line containing two item names followed by a positive integer (): the first name is the item Jack wants, the second name is the item Jack is willing to trade, and is the number of available trades. Each of the next lines has the form
a1 name1 a2 name2
meaning that some friend is willing to give units of item name1 in exchange for units of item name2 (the friend gives name1 and receives name2; the reverse trade is not implied). Each of and is a positive integer at most . No trade ever requires more than items to complete.
Output
For each test case, print Case i: (where is the case number, starting at ), followed by a space, the best ratio Jack can obtain, a single space, and the number of distinct ways Jack could obtain that ratio.
The ratio is written in ordinary decimal (fixed-point) notation, never in scientific notation, rounded to significant digits with trailing zeros kept, exactly as in the examples (e.g. 1.8000, 0.28571). A value lying exactly halfway between two -significant-digit results is rounded up.