NYOJ-21 三个水杯(BFS)

给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
题目链接: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值