您的位置:首页 > 其它

NYOJ-21 三个水杯(BFS)

2017-04-01 18:03 330 查看
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=21

用广度搜索算法就能做出了

#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
struct cup {
int wat[3];
int step;
};

bool p[100][100][100];//判断是否出现该种情况

int main()
{
cup thcu;
int max[3];
int goa[3];
int i,j;
int n;
cin>>n;
while(n>0)
{
queue<cup> myque;
memset(p,0,sizeof(p));
while(!myque.empty()) {myque.pop();}
n--;
cin>>max[0]>>max[1]>>max[2];
cin>>goa[0]>>goa[1]>>goa[2];
thcu.wat[0]=max[0];
thcu.wat[1]=0;
thcu.wat[2]=0;
thcu.step=0;
p[thcu.wat[0]][thcu.wat[1]][thcu.wat[2]]=1;
myque.push(thcu);
while(1)
{
if(myque.empty()) {cout<<-1<<endl;  break;}
thcu=myque.front();
if(thcu.wat[0]==goa[0]&&thcu.wat[1]==goa[1]&&thcu.wat[2]==goa[2]){
cout<<thcu.step<<endl;
break;
}//找到目标情况
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(i==j) continue;//排除对自身倒水
if(thcu.wat[i]>=(max[j]-thcu.wat[j])){
thcu.wat[i]=thcu.wat[i]-max[j]+thcu.wat[j];
thcu.wat[j]=max[j];
thcu.step++;
}
else if(thcu.wat[i]<(max[j]-thcu.wat[j])){
thcu.wat[j]=thcu.wat[j]+thcu.wat[i];
thcu.wat[i]=0;
thcu.step++;
}//倒水过程
if(p[thcu.wat[0]][thcu.wat[1]][thcu.wat[2]]==0)
{
p[thcu.wat[0]][thcu.wat[1]][thcu.wat[2]]=1;
myque.push(thcu);
}//未出现情况进队列
thcu=myque.front();
}
}
myque.pop();//计算所有情况后出队列
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs 算法