Milk Pails
InterviewTime limit2sMemory limit512 MB
Fill, empty, and pour two pails of sizes X and Y within K moves to get a combined amount as close to M as possible.
- Level
Medium4 of 10
- Topics
- BFS, Simulation
- Solved
- No attempts yet
Problem
Farmer John has an order for exactly units of milk () and has to fill it right away. His milking machine just broke, so all he has left are two milk pails of integer sizes and (). Both pails start out empty. With these two pails he can perform up to operations () of the following types.
- Fill one pail completely to the top.
- Empty one pail.
- Pour the contents of one pail into the other, stopping when the pouring pail becomes empty or the receiving pail becomes full, whichever happens first.
The total in the two pails may never be exactly . Compute the minimum value of over every total that Farmer John can leave in the two pails.
Input
The first and only line contains , , , and , separated by spaces.
Output
Print the smallest distance from to a total that Farmer John can produce.
Hint
For , , , and , two operations leave the following amounts in the pails.
(0, 0) = 0
(14, 0) = 14
(0, 50) = 50
(0, 14) = 14
(14, 36) = 50
(14, 50) = 64
The totals closest to 32 are 14 and 50, both at a distance of 18. Reaching (0, 36) would take one more operation to empty the first pail.