• Fill any of the jugs entirely with water.
• Empty any of the jugs.
• Pour water from one jug into another till the other jug is full, or the first jug itself is empty.
In order to measure 2 litres from jugs of 4 and 6 litres we can follow the following steps-
• Fill 6-litres jugs to its maximum capacity.
• Pour water from 6-litres jug to the jug with 4-litres capacity.
• Pour water from 6-litres jug to the jug with 4-litres capacity.
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test cases follow.
The first line of each test case contains three space-separated integers ‘X’, ‘Y’ and ‘Z’ denoting the capacities of both the jugs and the target measure, respectively.
For each test case, print True if we can measure the required value else, print False.
Output for each test case will be printed in a new line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5 * 10^4
0 <= X, Y, Z <= 5 * 10^4
Time Limit: 1 sec
We will run a breadth-first search(BFS), keeping states as water present in both the jugs. We will visit all the states, keeping a hashmap for visited states to not revisit the same state. If we reach a state such that the capacity of water in one of the jugs is equal to ‘Z’ liters or the sum of water in both the jugs is equal to ‘Z’ liters we return true else we return false.
Below is the detailed algorithm:
The above problem can be modelled by Diophantine equation ‘A’ * ‘X’ + ‘B’ * ‘Y’ = ‘Z’, where ‘A’ and ‘B’ are integers.
According to linear algebra, this equation is solvable if and only if the greatest common divisor of ‘X’ and ‘Y’ divides ‘Z’.
Hence, the conditions to measure exactly ‘Z’ litres will be-
Distance to a Cycle in Undirected Graph
Ninja And The Strictly Increasing Array
Maximum GCD
Prime?
Co-Prime