倒水问题
2016-04-11 19:31
561 查看
给定A, B两个桶。
可以不停地向A, B中倒水,也可以将B中的水倒入A中,或者将A中的水倒入B中,还可以清空A,B。
目标是 B桶中恰好有N加仑的水。
数据是3, 5 ,4
输出 倒水方式。
3 5 4
fill B
pour B
empty A
pour B
fill B
pour B
success
可以不停地向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
相关文章推荐
- 第三次上机实验2
- centos下django1.9部署
- mysql数据库中find_in_set()和in()用法区别
- plsql学习的心得
- JSP连接MySQL数据库和sql server数据库
- VS2013MFC对话框工程学习笔记七 - C++数据类型 - 整形 的简单学习
- margin设置div与div间距
- Linux内核中的红黑树
- 新开博客
- Microsoft Component Object Model (COM)介绍
- ios 图片加水印
- HDU 4407 12年金华网络赛H题(容斥原理)
- HDFS异构存储
- jQuery-:contains("")查询包含值的用法实例
- POJ 3041(最小点覆盖)
- 回掉函数
- Udev:介绍现代Linux系统的设备管理
- UVA 101 The Blocks Problem【vector】
- 解决undefined reference to `__fdelt_chk@GLIBC_2.15'的问题
- ionic入门教程第六课-从服务器请求数据的几种方式$http.get()、jsonp()分别和callback、$q的组合