习题原文:
Pouring water. We have three containers whose sizes are 10 pints, 7 pints, and 4 pints, re-spectively. The 7-pint and 4-pint containers start out full of water, but the 10-pint container is initially empty. We are allowed one type of operation: pouring the contents of one container into another, stopping only when the source container is empty or the destination container is full. We want to know if there is a sequence of pourings that leaves exactly 2 pints in the 7- or 4-pint container.
(a) Model this as a graph problem: give a precise definition of the graph involved and state the specific question about this graph that needs to be answered.
(b) What algorithm should be applied to solve the problem?
(c) Find the answer by applying the algorithm.
大致意思就是,有三个容器,分别可以装10品拖、7品拖、4品拖水。一开始,7品拖、4品拖的容器里水都是满的,10品拖的容器里是空的。我们只允许这样的操作:将水倒到另一个容器里,只有倒出水的桶空了或者接收水的桶慢了才能停止。请问,是否有一种可能性,使得7品拖和4品拖的容器里都留着2品拖水。
题目让我们把这个问题建一个图的模型,并且找出一种算法解决这个问题。
下面是我的解法:
思路:
如题所述的话,最终三个桶的状态是(7,2,2)。我们就把三个桶的所有可能的状态看成是一个图,每种状态是一个节点,那么根节点就是(0,7,4),我们要解决的问题就是,这个从这个根节点是否能到达(7,2,2)这个节点。这是一个连通性的问题,我们可以通过从(0,7,4)节点开始的深度优先遍历来解决这个问题。