Currency Exchange
You finally get into the casino, and the first thing you need to do is buy chips. You approach the machine and buy white chips, but then notice something strange. The machine will let you convert between different kinds of chips at different rates. For example:
white chip
red chips
red chip
blue chips
blue chip
white chip
Something strikes you as odd about these exchange rates. They're not fair! In the above example, starting with white chips:
- Convert them all to red chips. You how have
red chips.
- Convert them all to blue chips. You now have
blue chips.
- Convert them all to white chips. You now have
white chips.
And now, you've ended up with times more than your starting number of white chips!
However, the people behind you in line are impatient, and will only let you make at most exchanges. What is the maximum number of white chips you can get from these exchanges?
Input
The first line consists of an integer
, the number of white chips you start with.
The second line consists of an integer
, the number of exchanges you are allowed to make.
The third line consists of an integer
, the number of types of exchanges that the machine offers.
The next lines contain
,
, and
, meaning that one
chip is equivalent to
chips. The strings
and
are the names of the chips, while
is an integer representing the conversion rate.
Output
Output the maximum number of white chips you can make from these exchanges, rounded down to the nearest chip.
Clarifications
- Exchanges are offered only unidirectionally.
- No exchanges will be for a chip and itself.
- You must end up with white chips at the end of your exchanges.
- You don't need to use all your exchanges.
Example
Input
10
3
3
White 2 Red
Red 3 Blue
Blue 1 White
Output
60
This is simply the example above. is the maximum number of white chips you can get within the allowed
exchanges.
Input
1
7
5
White 2 Red
Red 2 Blue
Blue 2 White
Red 3 Green
Green 2 Blue
Output
192
Convert:
- White to red =
red chips
- Red to green =
green chips
- Green to blue =
blue chips
- Blue to white =
white chips
- White to red =
red chips
- Red to blue =
blue chips
- Blue to white =
white chips
This is the maximum number of chips you can obtain with exchanges.
Input
100
10
2
Red 2 Blue
Blue 2 White
Output
100
You can't convert your white chips to anything else, so you are stuck with .
Comments