您的位置:首页 > 其它

倒水问题

2016-04-11 19:31 561 查看
给定A, B两个桶。

可以不停地向A, B中倒水,也可以将B中的水倒入A中,或者将A中的水倒入B中,还可以清空A,B。

目标是 B桶中恰好有N加仑的水。

数据是3, 5 ,4

输出 倒水方式。

#include<iostream>
#include<cstring>

using namespace std;
struct condition
{
int a,b;//当前两个水壶各有多少升水
int father,mean;//father表示搜索到当前状态下的父亲状态在队列中的下标,mean表示父亲是怎么到达当前状态的
};
int A,B,N;
condition Q[10000];//队列,因为要保留父亲状态,输出方案是还会用到这个队列,所以不能用容器queue
void ready()
{
for(int i=0;i<10000;i++)
Q[i].a=Q[i].b=Q[i].father=Q[i].mean=0;
}
void Print(int x)
{
if(x==-1)
return;
else
Print(Q[x].father);
switch(Q[x].mean)
{
case 1:cout<<"fill A"<<endl;break;
case 2:cout<<"fill B"<<endl;break;
case 3:cout<<"pour A"<<endl;break;
case 4:cout<<"pour B"<<endl;break;
case 5:cout<<"empty A"<<endl;break;
case 6:cout<<"empty B"<<endl;break;
}
}
void BFS()
{
if(B==N)
{
cout<<"fill B"<<endl;
cout<<"success"<<endl;
}
ready();
int head=0,tail=0;
Q[tail].a=A;
Q[tail].father=-1;
Q[tail].mean=1;
tail++;//有可能是先对A操作,也有可能先对B操作,所以有两个起点
Q[tail].b=B;
Q[tail].father=-1;
Q[tail].mean=2;
tail++;

while(head<tail)
{
condition con;
con=Q[head];
head++;
if(con.a<A)//fill A
{
condition buf=con;
buf.a=A;
buf.mean=1;
buf.father=head-1;
Q[tail]=buf;
tail++;
}
if(con.b<B)//fill B
{
condition buf=con;
buf.b=B;
buf.mean=2;
buf.father=head-1;
Q[tail]=buf;
tail++;
}
if(con.a>0&&con.b<B)//pour A B
{
condition buf=con;
int tmp=min(buf.a,B-buf.b);
buf.a-=tmp;
buf.b+=tmp;
buf.father=head-1;
buf.mean=3;
Q[tail]=buf;
if(buf.b==N)
{
Print(tail);
break;
}
tail++;
}
if(con.b>0&&con.a<A)//pour B A
{
condition buf=con;
int tmp=min(buf.b,A-buf.a);
buf.b-=tmp;
buf.a+=tmp;
buf.father=head-1;
buf.mean=4;
Q[tail]=buf;
if(buf.b==N)
{
Print(tail);
break;
}
tail++;
}
if(con.a>0)//empty A
{
condition buf=con;
buf.a=0;
buf.father=head-1;
buf.mean=5;
Q[tail]=buf;
tail++;
}
if(con.b>0)//empty B
{
condition buf=con;
buf.b=0;
buf.father=head-1;
buf.mean=6;
Q[tail]=buf;
tail++;
}
}
}
int main()
{
while(cin>>A>>B>>N)
{
BFS();
cout<<"success"<<endl;
}
}


3 5 4

fill B

pour B

empty A

pour B

fill B

pour B

success
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: