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.

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

思路:小学的奥赛题,困扰了我好多年23333.

首先明确一个定理:

数论中,裴蜀等式英语:Bézout's identity)或裴蜀定理Bézout's lemma)是一个关于最大公约数(或最大公约式)的定理。裴蜀定理得名于法国数学家艾蒂安·裴蜀,说明了对任何整数abm,关于未知数xy线性丢番图方程(称为裴蜀等式):

ax+by=m

有整数解时当且仅当mab最大公约数d倍数。裴蜀等式有解时必然有无穷多个整数解,每组解xy都称为裴蜀数,可用扩展欧几里得算法求得。

例如,12和42的最大公约数是6,则方程12x+42y=6有解。事实上有(-3)×12 + 1×42 = 6及4×12 + (-1)×42 = 6。

特别来说,方程ax+by=1 有整数解当且仅当整数ab互素

对于本体而言,相当于Z = AX + BY,A、B 为整数。可以认为有一个特别大容器,x、y两个小容器,小容器既可以往大容器里倒水(A、B大于0),也可以往外舀水(A、B小于0)。如果等式有解,则返回true,否则返回false。

注意Z不能大于x + y,因为实际生活里x、y容器都装满水也不能超过x+y的容量。

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if(z > x + y) return false;//两个容器加起来也装不下
        if(x == z || y ==z || x + y == z) return true;//容器大小刚好等于需要的量
        return z % gcd(x,y) == 0 ?true:false; //裴蜀定理        
    }
    public int gcd(int x,int y){
        while(y != 0){
            int temp = y ;
            y = x % y;
            x = temp;
        }
        return x;
    }   
}


猜你喜欢

转载自blog.csdn.net/u013300579/article/details/79922978