NYOJ 21 三个水杯(bfs)

来源:互联网 发布:js给tbody添加行 编辑:程序博客网 时间:2024/04/29 22:02

三个水杯

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
输入
第一行一个整数N(0<N<50)表示N组测试数据
接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态

输出
每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1

样例输入
26 3 14 1 19 3 27 1 1

样例输出
3-1


这种隐式图的bfs几乎没做过,思维能力差得要命。 一定要好好练习。遍历所有倒水情况,满足情况是就终止。


代码即题解,如下:


#include<cstdio>#include<cstring>#include<queue>using namespace std;int v[5],e[5];int sign[110][110][110];struct cup//记录遍历中3个水杯水量情况 {int v[5];int step;}temp;void pour(int a,int b)//倒水函数,把a杯子中的水倒到b杯子中 {int sum=temp.v[a]+temp.v[b];if(sum>=v[b])temp.v[b]=v[b];elsetemp.v[b]=sum;temp.v[a]=sum-temp.v[b];}void bfs(){int i,j;queue<cup>q;cup cnt;memset(sign,0,sizeof(sign));temp.v[1]=v[1];temp.v[2]=0;temp.v[3]=0;temp.step=0;q.push(temp);sign[temp.v[1]][0][0]=1;while(!q.empty()){cnt=q.front();q.pop();if(cnt.v[1]==e[1]&&cnt.v[2]==e[2]&&cnt.v[3]==e[3]){printf("%d\n",cnt.step);return ;}for(i=1;i<4;++i){for(j=1;j<4;++j){if(i!=j)//自己不倒水给自己 {temp=cnt;//每个水位情况都要把所有操作枚举一遍,所以都要赋值为原始水位情况 pour(i,j);if(!sign[temp.v[1]][temp.v[2]][temp.v[3]]){temp.step++;q.push(temp);sign[temp.v[1]][temp.v[2]][temp.v[3]]=1;}}}}}printf("-1\n");}int main(){int t;scanf("%d",&t);while(t--){scanf("%d%d%d",&v[1],&v[2],&v[3]);scanf("%d%d%d",&e[1],&e[2],&e[3]);bfs();}return 0;} 





1 0