You are given two water jugs with capacities X and Y litres respectively. Both the jugs are initially empty. There is an infinite amount of water supply available. The jugs do not have markings to measure smaller quantities.
The following operations are allowed:
• 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.
You are required to tell whether it is possible to measure exactly ‘Z’ litres using both of the jugs.
If Z litres of water is measurable, you must have Z litres of water contained within one or both buckets by the end.
For example:
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.
Output Format :
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.
Note :
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
2
3 5 4
2 2 7
True
False
The following steps in test case 1 may be followed to measure 4 litres-
• Fill 5-litres jug to its maximum capacity.
• Transfer 3-litres from 5-litres jug to 3-litres jugs.
• Empty the 3-litres jug.
• Transfer 2-litres from 5-litres jug to 3-litres jug.
• Fill 5-litres jug to its maximum capacity.
• Pour water to 3-litres jug from 5-litres jug until it’s full.
We will find that exactly 4 litres will be left in the jug with 5 litres capacity.
There is no way in test case 2 that we can measure 7 litres from two 2-litres jugs.
1
8 6 14
True
Can we use BFS to solve this problem?
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:
O(X * Y), where X is the capacity of the first jug and Y is the capacity of the second jug.
The number of distinct states will be (X * Y). As in the worst case, we will be visiting all the states. Hence, time complexity will O(X * Y).
O(X * Y), where X is the capacity of the first jug and Y is the capacity of the second jug.
The space complexity due to the hashmap and the queue will O(X * Y).