题目如下:
In the movie "Die Hard 3", Bruce Willis and Samuel L. Jackson were confronted with the following puzzle. They were given a 3-gallon jug and a 5-gallon jug and were asked to fill the 5-gallon jug with exactly 4 gallons. This problem generalizes that puzzle.
You have two jugs, A and B, and an infinite supply of water. There are three types of actions that you can use: (1) you can fill a jug, (2) you can empty a jug, and (3) you can pour from one jug to the other. Pouring from one jug to the other stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons and B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A.
A problem is given by a triple (Ca,Cb,N), where Ca and Cb are the capacities of the jugs A and B, respectively, and N is the goal. A solution is a sequence of steps that leaves exactly N gallons in jug B. The possible steps are
fill A
fill B
empty A
empty B
pour A B
pour B A
success
where "pour A B" means "pour the contents of jug A into jug B", and "success" means that the goal has been accomplished.
You may assume that the input you are given does have a solution.
Input
Input to your program consists of a series of input lines each defining one puzzle. Input for each puzzle is a single line of three positive integers: Ca, Cb, and N. Ca and Cb are the capacities of jugs A and B, and N is the goal. You can assume 0 < Ca <= Cb and N <= Cb <=1000 and that A and B are relatively prime to one another.
Output
Output from your program will consist of a series of instructions from the list of the potential output lines which will result in either of the jugs containing exactly N gallons of water. The last line of output for each puzzle should be the line "success". Output lines start in column 1 and there should be no empty lines nor any trailing spaces.
Sample Input
3 5 4
5 7 3
Sample Output
fill B
pour B A
empty A
pour B A
fill B
pour B A
success
fill A
pour A B
fill A
pour A B
empty B
pour A B
success
简单来说就是我们以前做的智力题,有两个容积为a、b的罐子,要倒出c升水来,题目假设了a,b互素并且a<b,c<b.
根据欧拉定理:
若n,a为正整数,且n,a互质,则(其中φ(n)为欧拉函数):a^(φ(n))同余1(mod n)
题目中a,b互质,如此一来也就是存在正整数k=a^(φ(b)-1),使得k*a mod b=1.
这样只需要从a向b倒水,b满了就倒空,最终能够得到1升水,将这个行为重复c次就能得到c升水。
以上只是说明了可行性,事实上在实际操作很容易发现并不需要那么多次的操作,例如,7 和 5,根据欧拉定理,(7^4)*7 mod 5=1,不过稍加计算就发现7*3 mod 5=1,所以只需要三次操作就得到了1升水。
在代数学有一个定理,对任意两个多项式f(x)和g(x),若他们最大公因式为d(x),那么d可以表示为f 、g的一个组合,即:
存在多项式u,v使得d=uf+vg
代数里面多项式是对整数更高层的推广,以上定理中的多项式可以完全改为整数。
显然1是a,b的最大公因式,那么存在整数e,f,使得1=ea+fb.
e和f至少一个是负数,如果e是负数,那么只需要从a向b倒水,b满了就倒空,最终能够得到1升水。
不过此处有个小问题,并不能解释为什么我们从小罐子向大罐子倒水总能获得成功。
需要进一步证明,已知b>a,如果e<0,f>0;由1=ea+fb,可以推知1=(e+kb)a+(f-ka)b,取一个充分大的k就能使得e+kb>0,(f-ka)<0.得证
以上两种方法都只是从某些侧面看待问题,得到的结论不是问题的本质,我们会发现用ka 去mod b,当k从0开始取到b-1,得到的模数会包含a,b最大公因数的所有倍数 mod b。这显然不是巧合,可以用python简单验证一下:
for i in range(12):{print((i*9)%12)}
输出:
0
{None}
9
{None}
6
{None}
3
{None}
0
{None}
9
{None}
6
{None}
3
{None}
0
{None}
9
{None}
6
{None}
3
{None}
可以看出包含了0,3,6,9
这一点可以从以下欧几里得算法看出来