题目:
倒水问题 “fill A” 表示倒满A杯,"empty A"表示倒空A杯,“pour A B” 表示把A的水倒到B杯并且把B杯倒满或A倒空。
Input:
输入包含多组数据。每组数据输入 A, B, C 数据范围 0 < A <= B 、C <= B <=1000 、A和B互质。Output你的程序的输出将由一系列的指令组成。这些输出行将导致任何一个罐子正好包含C单位的水。每组数据的最后一行输出应该是“success”。输出行从第1列开始,不应该有空行或任何尾随空格。
Sample Input:
2 7 5
2 7 4
Sample Out:
putfill B
pour B A
success
fill A
pour A B
fill A
pour A B
success
Notes:
如果你的输出与Sample Output不同,那没关系。对于某个"A B C"本题的答案是多解的,不能通过标准的文本对比来判定你程序的正确与否。 所以本题由 SPJ(Special Judge)程序来判定你写的代码是否正确。
思路:
将A与B杯中水的剩余量当作平面直角坐标系上的一个点,则每经过一次操作后A与B杯中水的变化即可看作是平面由一个点到另外一个点的变化。而使杯中状态变化的操作只有六种:倒满A、倒满B、倒空A、倒空B、由A倒向B、由B倒向A。
将A,B中的状态水量用结构体status表示,其中status结构体中的字符串c记录下该状态是经过什么操作形成的,并将操作之前的状态存放在map中,便于回溯输出。然后定义一个队列Q,当Q不为空时,取出队首元素,遍历六种操作,将得到而且没有到达过的A,B水量状态压入队列之中,不断重复上述操作直到A,B中至少有一个水量刚好等于目标水量C时(即bfs广度优先搜索),即可通过递归输出由起始状态到达目标状态进行的操作(即status中的c)。
代码:
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct status
{
int a, b;
string c;
bool operator<(const status &s) const
{
return a != s.a ? a < s.a : b < s.b;
}
};
queue<status> Q;
map<status, status> from;
vector<status> v;
void print(status p)
{
if (from.find(p) == from.end()||(p.a==0&&p.b==0))
{
cout << p.c << endl;
return;
}
print(from[p]);
cout << p.c << endl;
}
void refresh(status &s, status &t)
{
if (from.find(t) == from.end())
{
from[t] = s;
Q.push(t);
}
}
void bfs(int a, int b, int c)
{
status s, t; s.a = 0; s.b = 0;
Q.push(s);
while (!Q.empty())
{
s = Q.front();
Q.pop();
if (s.a == c || s.b == c)
{
s.c = "success";
print(s);
break;
}
if (s.a > 0)
{
t.a = 0;
t.b = s.b;
s.c = "empty A";
refresh(s, t);
}
if (s.b > 0)
{
t.b = 0;
t.a = s.a;
s.c = "empty B";
refresh(s, t);
}
if (s.a<a)
{
t.a = a;
t.b = s.b;
s.c = "fill A";
refresh(s, t);
if (s.b != 0)
{
if (s.a + s.b <= a)
{
t.a = s.a + s.b;
t.b = 0;
s.c = "pour B A";
refresh(s, t);
}
else
{
t.a = a;
t.b = s.a + s.b - a;
s.c = "pour B A";
refresh(s, t);
}
}
}
if (s.b < b)
{
t.a = s.a;
t.b = b;
s.c = "fill B";
refresh(s, t);
if (s.a != 0)
{
if (s.a + s.b <= b)
{
t.a = 0;
t.b = s.a + s.b;
s.c = "pour A B";
refresh(s, t);
}
else
{
t.a = s.a + s.b - b;
t.b = b;
s.c = "pour A B";
refresh(s, t);
}
}
}
}
}
int main()
{
int a, b, c;
while (1)
{
if (scanf("%d", &a) == EOF)
break;
cin >> b >> c;
while (!Q.empty())
{
Q.pop();
}
from.clear();
bfs(a, b, c);
}
return 0;
}