week2作业B

题意:
倒水问题 “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
Notes:
如果你的输出与Sample Output不同,那没关系。对于某个"A B C"本题的答案是多解的,不能通过标准的文本对比来判定你程序的正确与否。 所以本题由 SPJ(Special Judge)程序来判定你写的代码是否正确。
思路:
定义一个结构体,里面定义两个杯子中的量。有六种状态,fill A,fill B,empty A,empty B,pour A B,pour B A存储在一个数组中。定义在六种不同的状态中,分别如何进行实现。在empty状态下直接让它为0,在fill状态下,让两个瓶子中的水都为其满时的量。在pour状态中,当pour A B时,如果a杯中的水不为0时,如果两杯的水现有的量相加大于b杯的容量时,b杯的量为满时的量,而a杯中的量为倒满b杯后剩余的量。如果两杯中现有的量小于等于b杯的容量时,b杯的量为两杯现有的量的和,而a杯为空。通过bfs进行判断,将得出的结果压入到容器中,如果实现a杯或b杯中现有的量为所求的量时则输出容器中存储的顺序结果。
代码:
#include
//#include
#include
#include
#include
#include
using namespace std;
string temp[6]={“fill A”,“empty A”,“fill B”,“empty B”,“pour A B”,“pour B A”};
//int vis[1005][1005];
struct Node
{
int bottlea,bottleb;
vector temp;
};
void bfs(int a,int b,int c)
{
int vis[1000][1000]={0};
queue q;
struct Node node;
node.bottlea=0;
node.bottleb=0;
q.push(node);
vis[0][0]=1;
memset(vis,0,sizeof(vis));
while(!q.empty())
{
node=q.front();
q.pop();
for(int i=0;i<6;i++)
{
struct Node now=node;
switch(i)
{
case 0:
now.bottlea=a;
break;
case 1:
now.bottlea=0;
break;
case 2:
now.bottleb=b;
break;
case 3:
now.bottleb=0;
break;
case 4:
if(now.bottlea!=0)
{
if(now.bottlea<=b-now.bottleb)
{
now.bottleb=now.bottleb+now.bottlea;
now.bottlea=0;
}
else
{
now.bottlea=now.bottlea+now.bottleb-b;
now.bottleb=b;
}
}
break;
case 5:
if(now.bottleb!=0)
{

             if(now.bottleb+now.bottlea<=a)
             {
              now.bottlea=now.bottlea+now.bottleb;
              now.bottleb=0;
 }
 else
 {
  now.bottleb=now.bottleb+now.bottlea-a;
  now.bottlea=a;
 }
 }
 break;

}
now.temp.push_back(i);
if(now.bottlebc||now.bottleac)
{
for (vector::iterator tem = now.temp.begin(); tem != now.temp.end(); tem++){
cout << temp[*tem] << endl;}
cout<<“success”<<endl;
return;
}
else
{
if(!vis[now.bottlea][now.bottleb])

    q.push(now);
vis[now.bottlea][now.bottleb]=true;

}
}
}
}
int main()
{
int A,B,C;
//while(scanf("%d%d%d",&a,&b,&c))
while(cin>>A>>B>>C)
{
bfs(A,B,C);
}
return 0;
}

发布了19 篇原创文章 · 获赞 0 · 访问量 221

猜你喜欢

转载自blog.csdn.net/weixin_45117273/article/details/104738476