LeetCode 365 Water and Jug Problem

来源:互联网 发布:乌克兰 知乎 编辑:程序博客网 时间:2024/05/21 05:55

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 zlitres 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 = 4Output: True

Example 2:

Input: x = 2, y = 6, z = 5Output: False

题意:

给定两个容量分别为x和y升的罐子。提供无限容量的水。你需要判断用这两个罐子是否可以恰好量出z升的体积。到最后量出的z升体积可以由一到两个罐子装着。

允许的操作包括:

1、将任意罐子灌满。

2、将任意罐子清空。

3、将任意罐子的水倒入另一个罐子,直到另一个罐子倒满或者自己为空为止。


题意相当于求出:整数x、y只通过不断的加减运算,是否可以得到z。等价为ax+by=z是否成立,其中a,b为整数并且为负。

c为x、y的最大公约数,则x/c、y/c都为整数,分别设m=x/c,n=y/c,请看以下证明过程:

   ax+by

=a*c*x/c+b*c*y/c 

=a*c*m+b*c*n

= a'*c+b'*c   (设a'=a*m,b'=b*n)

= (a'+b')*c。

ax+by== (a'+b')*c,其中c为x,y的最大公约数,a',b'为整数,若z = ax+by=(a'+b')*c,则z必须可以整除c,因此题意又等价于,判断z是否可以整除x,y的最大公约数。

public boolean canMeasureWater(int x, int y, int z) {return z == 0 || (z <= x + y && z % getGcd(x, y) == 0);}/** * 最大公约数 */private int getGcd(int a, int b) {return b == 0 ? a : getGcd(b, a % b);}


1 0