本文主要是介绍NYOJ 21 三个水杯(BFS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
描述
- 输入
- 第一行一个整数N(0<N<50)表示N组测试数据
接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态 输出 - 每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1 样例输入
-
2 6 3 1 4 1 1 9 3 2 7 1 1
样例输出 -
3 -1
宽度优先搜索,三个水杯之间的相互倒水如下图6种情况:
对于每一次倒水都会引起三个水杯水量状态的改变,这样就可以得到如下的一个解空间树:
自己一开始也没有头绪,看别人的博客,学习一下别人的经验才做出来的。在网上看到这个图解释的很清楚就借用一下。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
struct node
{int step;int state[3];bool operator <(const node &a) const{return a.step<step;}
};
//三个水杯当前的状态
int curcup[3];
//目标状态
int endcup[3];
//三个水杯最大装水数
int maxcup[3];
int book[101][101][101];
//i水杯向j水杯倒水
void pourwater(int i,int j)
{//如果j水杯是满的 或者 i水杯没水 返回if(curcup[i]==0||curcup[j]==maxcup[j])return ;//如果i水杯当前的水容量大于j水杯空着的容量if(curcup[i]>=(maxcup[j]-curcup[j])){curcup[i]=curcup[i]-(maxcup[j]-curcup[j]);curcup[j]=maxcup[j];}//如果i水杯当前的水容量小于水杯空着的容量else{curcup[j]+=curcup[i];curcup[i]=0;}
}
int bfs()
{priority_queue<node>Q;while(!Q.empty())Q.pop();node temp,temp1;temp.state[0]=maxcup[0];temp.state[1]=temp.state[2]=temp.step=0;book[maxcup[0]][0][0]=1;Q.push(temp);while(!Q.empty()){temp=temp1=Q.top();Q.pop();if(temp.state[0]==endcup[0]&&temp.state[1]==endcup[1]&&temp.state[2]==endcup[2])return temp.step;curcup[0]=temp.state[0];curcup[1]=temp.state[1];curcup[2]=temp.state[2];for(int i=0; i<=2; i++){for(int j=0; j<=2; j++){if(i!=j)//模拟6种倒水的方式(3*3-3){pourwater(i,j);temp.state[0]=curcup[0];temp.state[1]=curcup[1];temp.state[2]=curcup[2];temp.step++;if(book[curcup[0]][curcup[1]][curcup[2]]==0){book[curcup[0]][curcup[1]][curcup[2]]=1;Q.push(temp);}temp=temp1;curcup[0]=temp.state[0];curcup[1]=temp.state[1];curcup[2]=temp.state[2];}}}}return -1;
}
int main()
{int t,i;scanf("%d",&t);while(t--){memset(book,0,sizeof(book));for(i=0; i<3; i++)scanf("%d",&maxcup[i]);for(i=0; i<3; i++)scanf("%d",&endcup[i]);printf("%d\n",bfs());}return 0;
}
这篇关于NYOJ 21 三个水杯(BFS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!