Water and Jug Problem

题目
You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

Operations allowed:

Fill any of the jugs completely with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

答案

这个题目其实如果给了hint (ax + by = d = gcd(x,y))的话应该很快可以想到解法,不然的话只能走暴力搜索。

思路是这样
给定2个瓶子,容量分别为x和y

然后我们定义几个变量
d = 在游戏结束,还留在瓶子里的水的总和
x = 把一个瓶子从没有水到灌满(2x就是把这个动作做两次)
y = 把另一个瓶子从没有水到灌满
注意,将一个瓶子里的水倒进另一个瓶子并不影响t的数量

那么,如果d = ax + by, 就证明有一系列的灌水和清空水的动作可以使得最后水瓶里的水为d
那么,如果z是d的倍数,就证明有一系列的灌水和清空水的动作可以使得最后水瓶里的水为z, 因为z = cd = c(ax+by) = acx + bcy

再考虑上一些edge case之后,代码如下

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if(x == 0) return y == z || x == z;
        if(y == 0) return x == z || y == z;
        if(z == 0) return true;
        return z % gcd(x, y) == 0 && (x + y >= z);
    }
    
    public int gcd(int x, int y) {
        if(y == 0) return x;
        return gcd(y, x % y);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容