NYOJ(21),BFS,三个水杯

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

BFS判环,vis标记状态即可。

#include <stdio.h>
#include <queue>
#include <string.h>

using namespace std;

bool vis[100][100][100];

struct Cup
{
    int v[3];
    int step;
};

int s[3],t[3];

int bfs()
{
    memset(vis,false,sizeof(vis));
    Cup start;
    start.step = 0;
    start.v[0] = s[0];
    start.v[1] = 0;
    start.v[2] = 0;
    vis[s[0]][0][0] = true;
    queue<Cup> Q;
    Q.push(start);
    while(!Q.empty())
    {
        start = Q.front();
        Q.pop();
        if(start.v[0]==t[0]&&start.v[1]==t[1]&&start.v[2]==t[2])
            return start.step;

        for(int i=0; i<3; i++)
        {
            for(int j=0; j<3; j++)
            {
                Cup tmp = start;
                if(i==j||tmp.v[i]==0||tmp.v[j]==s[j])
                    continue;


                if(tmp.v[i]+tmp.v[j]<=s[j])
                {
                    tmp.v[j] = tmp.v[i]+tmp.v[j];
                    tmp.v[i] = 0;
                }
                else
                {
                    tmp.v[i] = tmp.v[i] - (s[j]-tmp.v[j]);
                    tmp.v[j] = s[j];
                }
                tmp.step++;
                if(!vis[tmp.v[0]][tmp.v[1]][tmp.v[2]])
                {
                    Q.push(tmp);
                    vis[tmp.v[0]][tmp.v[1]][tmp.v[2]] = true;
                }
            }
        }
    }
    return -1;
}

int main()
{
    int cases;
    scanf("%d",&cases);
    while(cases--)
    {
        for(int i=0; i<3; i++)
            scanf("%d",&s[i]);
        for(int i=0; i<3; i++)
            scanf("%d",&t[i]);
        printf("%d\n",bfs());
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/TreeDream/p/5742186.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值