lance6716

Untitled

Jul 12th, 2019
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. class Solution:
  2.     """
  3.    @param x: the given number x
  4.    @param y: the given number y
  5.    @param z: the given number z
  6.    @return: whether it is possible to measure exactly z litres using these two jugs
  7.    """
  8.     def canMeasureWater(self, x, y, z):
  9.         # Write your code here
  10.         '''
  11.        easily get z is legal => z = M * x + N * y and 0 <= z <= x + y
  12.        
  13.        prove converse proposition:
  14.        if z >= x, we could pour x-jug full and empty it, z' = z - x, M -= 1, z' is legal
  15.        if z <= x, we could pour all water to x-jug and fill y-jug, z' = z + y, N += 1, z' is legal
  16.        similar with z >= y, N -= 1, z <= y, M += 1
  17.        
  18.        for given z = M * x + N * y and 0 <= z <= x + y, it must be
  19.        1. M == 1 and N == 1, easily comes z is legal
  20.        2. M > 0 and N < 0, by transform of M -= 1 and N += 1, one of M or N will
  21.           firstly reach 0. it can't be M since now z = N * y < 0 not legal. so N
  22.           will firstly reach 0 and z = M * x, and M -= 1 * M now z is 0, a legal
  23.           initiation status.
  24.        3. M < 0 and N > 0. similar
  25.        '''
  26.         return z % math.gcd(x, y) == 0 and 0 <= z <= x + y
Advertisement
Add Comment
Please, Sign In to add comment