题目:倒水问题
网址:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=18&page=show_problem&problem=1544
There are three jugs with a volume of a, b and c liters. (a, b, and c are positive integers not greater
than 200). The first and the second jug are initially empty, while the third is completely filled with
water. It is allowed to pour water from one jug into another until either the first one is empty or the
second one is full. This operation can be performed zero, one or more times.
You are to write a program that computes the least total amount of water that needs to be poured;
so that at least one of the jugs contains exactly d liters of water (d is a positive integer not greater
than 200). If it is not possible to measure d liters this way your program should find a smaller amount
of water d
′ < d which is closest to d and for which d
′
liters could be produced. When d
′
is found, your
program should compute the least total amount of poured water needed to produce d
′
liters in at least
one of the jugs.
The first line of input contains the number of test cases. In the next T lines, T test cases follow. Each
test case is given in one line of input containing four space separated integers — a, b, c and d.
The output consists of two integers separated by a single space. The first integer equals the least total
amount (the sum of all waters you pour from one jug to another) of poured water. The second integer
equals d, if d liters of water could be produced by such transformations, or equals the closest smaller
value d
′
that your program has found.
这道题可以使用优先队列BFS解决。
不难清楚,状态就是(a,b,c)代表三个容器中的当前水量(注意:顺序有差别)。
状态就是(a,b,c),直接跑一遍BFS即可。
核心在于,该状态记录起来过于繁琐,如何简化状态?
显然:总水量是定值,那么只要前两个容器水量确定,就可以刻画出了整个状态!所以状态数组仅需二维即可。该状态下需要判重。
代码如下:
该道题启示我们可以发掘一些隐含的条件来简化状态,从而简化时间及空间的复杂度。