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.
Example 1: (From the famous "Die Hard" example)
Input: x = 3, y = 5, z = 4 Output: True
Example 2:
Input: x = 2, y = 6, z = 5 Output: False
有两个罐子,容积分别为x升和y升。现水源充足,需要判断是否可用这两个罐子量出z升水。z升水可在这2个罐子中的任意一个或两个。
想了好久,不会做,惭愧啊!
以下参考一位大神的解答,感谢大神分享!
大神说不要折腾在这两个罐子里相互倒水(我就是在这里折腾-_-|||,哎。。。),假设另有一个足够大的桶,设为k,现在我们用上面那两个罐子(容积分别为x,y)往k里倒进水或从k里盛出水,经过一系列操作后,问能不能使k里剩余z升水?这就转化为方程:
z=mx+ny……………………(1)
是否存在解m、n。其中m、n均为整数,表示取水次数,正数表示往k里倒水,负数表示从k里盛出水。例如:4=(-2)*3+2*5 表示用5升的罐子往k里倒了2次,用3升的罐子从k里盛出2次。
答案是存在。根据裴蜀定理,对于非0整数x,y,若d是它们的最大公约数,存在整数a,b,使ax+by=d。因此,方程(1)是否存在解m、n,转化为z是否能被x,y的最大公约数整除。问题就简单了,代码如下:
int gcd(int x, int y)
{
return y == 0 ? x : gcd(y, x%y);
}
bool canMeasureWater(int x, int y, int z)
{
return z == 0 || (x + y >= z && z % gcd(x, y) == 0);
}
浙公网安备 33010602011771号