简要阐述:
在我们解决图的问题的时候,普遍遇到的是给出明显的图,然后解决路径问题。但是也经常能看到比如:小船过河(农夫、白菜、狼、羊)、杯子倒水等问题。今天要解决的问题就是 杯子倒水的问题。
用两个杯子,容量分别为A、B,去倒出C容量的水。这样只需要将两个杯子的水容量当成一种状态,最后的状态就是其中一个杯子中盛放C容量的水。
具体题目:
倒水问题 "fill A" 表示倒满A杯,"empty A"表示倒空A杯,
"pour A B" 表示把A的水倒到B杯并且把B杯倒满或A倒空。
输入:
输入包含多组数据。每组数据输入 A, B, C 数据范围 0 < A <= B 、C <= B <=1000 、A和B互质。
输出:
你的程序的输出将由一系列的指令组成。这些输出行将导致任何一个罐子正好包含C单位的水。每组数据的最后一行输出应该是“success”。输出行从第1列开始,不应该有空行或任何尾随空格。
解题分析:
1.首先要解决的是杯子各种状态的转换。
在地图中点与点转换是简单的:上、下、左、右。
但是在倒水问题中细分下来有六种状态转换:
1)A杯水倒空
2)B杯水倒空
3)A杯水倒满
4)B杯水倒满
5)A杯水倒入B杯
6)B杯水倒入A杯
我们使用一个struct类型记录A杯和B杯
struct node{
int a;intb;
}
具体的代码是:
//倒空a的水
if(now.x>0){
theNew.x=0;
theNew.y=now.y;
refresh(now,theNew);
}
//a没有满,加满a
if(now.x<A)
{
//加满A
theNew.x=A;
theNew.y=now.y;
refresh(now,theNew);
//将b的水倒入a
if(now.y!=0)
{
if(now.y+now.x<=A)//两个杯子的水加起来无法充满A,B杯的水全部加入A杯
{
theNew.x=now.x+now.y;
theNew.y=0;
refresh(now,theNew);
}
else//两个杯子的水加起来无法充满A,B杯的水一部分加满A杯,剩下x+y-A的水
{
theNew.x=A;
theNew.y=now.y+now.x-A;
refresh(now,theNew);
}
}
}
2.第二个问题就是如何记录每次操作的过程:
利用一个二维数组就行了,在visit到状态t的时候,会将状态t拓展到状态s,只要用from[s]=t
就可以记录到t-->s这么一个路径了。
全部代码:
#include<stdio.h>
#include<map>
#include<queue>
using namespace std;
int A,B,C;
struct node
{
int x;int y;
bool operator < (const node &s)const
{
return x!=s.x ? x<s.x : y<s.y;
}
};
queue<node> Q;
map<node,node> from;//记录路径
void refresh(node &t,node &s)
{
if(s.x==0&&s.y==0) return;
if(from.find(s)==from.end())//之前没有这种状态
{
Q.push(s);
from[s]=t;
}
}
void print_fun(node &t,node &s)
{
if(t.x==s.x)//cup B may change
{
if(s.y==B) printf("fill B\n");
else printf("empty B\n");
}
else if(t.y==s.y)
{
if(s.x==A) printf("fill A\n");
else printf("empty A\n");
}
else//两个杯子都有变化
{
if(s.x<t.x) printf("pour A B\n");
else printf("pour B A\n");
}
}
void print(node &n)
{
if(from.find(n)==from.end())//起点
{
return;
}
print(from[n]);
print_fun(from[n],n);
return;
}
void bfs()
{
//printf("enter\n");
node s1,theNew; s1.x=0;s1.y=0;
Q.push(s1);
while(!Q.empty())
{
//printf("here\n");
node now=Q.front();
Q.pop();
//判断终点
if(now.x==C||now.y==C)
{
//printf("end\n");
print(now);
return;
}
//倒空a的水
if(now.x>0){
theNew.x=0;
theNew.y=now.y;
refresh(now,theNew);
}
//倒空b的水
if(now.y>0){
theNew.y=0;
theNew.x=now.x;
refresh(now,theNew);
}
//a没有满,加满a
if(now.x<A)
{
theNew.x=A;
theNew.y=now.y;
refresh(now,theNew);
//将b的水倒入a
if(now.y!=0)
{
if(now.y+now.x<=A)
{
theNew.x=now.x+now.y;
theNew.y=0;
refresh(now,theNew);
}
else
{
theNew.x=A;
theNew.y=now.y+now.x-A;
refresh(now,theNew);
}
}
}
//b没有满,加满b
if(now.y<B)
{
theNew.y=B;
theNew.x=now.x;
refresh(now,theNew);
//将a的水倒入b
if(now.x!=0)
{
if(now.y+now.x<=B)
{
theNew.y=now.x+now.y;
theNew.x=0;
refresh(now,theNew);
}
else
{
theNew.y=B;
theNew.x=now.x+now.y-B;
refresh(now,theNew);
}
}
}
}
}
int main()
{
while(scanf("%d %d %d",&A,&B,&C)!=EOF)
{
while(!Q.empty()) Q.pop();
from.clear();
bfs();
printf("success\n");
}
return 0;
}