问题:
倒水问题 “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 output:
fill B
pour B A
success
fill A
pour A B
fill A
pour A B
success
题解:
-
BFS函数:
关于bfs函数的构造我们其实和迷宫问题一样,只不过我们将每一层的操作由上下左右走变为倒水的六种操作,之后就和最简单的bfs函数一样,将每一步操作的结果放入队列中,知道从队列中得到我们想要的结果。
迷宫问题 -
对于操作和父节点的记录
父节点的记录和迷宫问题一样,都是采用map函数进行记录,用每一个子节点对应其父节点,但是我们在创建对应关系时,应该检查该子节点是否已经存在过,也就是是否在map中已经存在,这样就可以避免我们死循环重复操作。 -
六种操作
对于六种操作的实现,我们只要对于操作完的状态弄清楚即可,对于pour a to b和pour b to a的操作需要判定我们我们杯子里的水和被子容量的关系。 -
输出
对于输出我们采用递归,从最后状态往前输出。
代码:
#include <iostream>
#include <queue>
#include <map>
#include <stdio.h>
#include <cstring>
using namespace std;
struct point //定义结构体
{
int a;
int b;
int choice;
bool operator<(const point &y) const{
//map函数需要的重载
if(a==y.a)
{
return b<y.b;
}
else
{
return a<y.a;
}
}
point(){
}
point(int thea,int theb,int thechoice){
a=thea;
b=theb;
choice=thechoice;
}
};
map<point,point> past;
string stringtochoice[7]