# 程序控

IPPP (Institute of Penniless Peasent-Programmer) Fellow

 博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::

Time limit: 3.000 seconds

## Background背景

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.

3 5 4
5 7 3

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

## Analysis分析

• r1 = mA mod B

• r2 = (r1 + nA) mod B
• = (mA mod B + nA) mod B
• = (m+n)A mod B

## Solution解答

#include <iostream>
#include <vector>
using namespace std;
int main(void) {
//循环处理输入的每行数据
for (int nACap, nBCap, nDest; cin >> nACap >> nBCap >> nDest; ) {
//开始循环从A到入B的算法，每次输出动作
for (int nA = 0, nB = 0; nB != nDest; cout << "pour A B\n") {
//如果A罐已空，则装满A罐，并输出动作
if (nA == 0) {
nA = nACap;
cout << "fill A\n";
}
//如果B罐已满，则倒空B罐，并输出动作
if(nB == nBCap) {
nB = 0;
cout << "empty B\n";
}
//将A罐全部倒入B罐
nB += nA;
nA = 0;
//若发现B罐超量，则将超过部分倒回A罐
if (nB > nBCap) {
nA = nB - nBCap;
nB = nBCap;
}
}
cout << "success" << endl;
}
return 0;
}


posted on 2010-08-04 16:08  Devymex  阅读(1378)  评论(0编辑  收藏