UVa OJ 10603 - Fill
Problem
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.
Input
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.
Output
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.
Sample Input
1 | 2 |
Sample Output
1 | 2 2 |
Solution
这是一个最短路径问题,利用BFS即可以得到答案。
主要还是需要注意运行时间问题,尽量将循环的范围缩小。同时,使用memset对字节进行操作也能起到提升速度的作用。
这里在做完题目以后恰好看到了Morris’s Blog,感觉他的代码格式看起来很舒服,也便于大家理解,因此将代码格式改得和他基本一样了,只做了一点微小的改动。大家可以也去他的Blog逛一逛,还是有很大收获的。
1 |
|