HLJOJ1021(倒水问题)



描述:设大,中,小三个杯子的容量分别为a,b,c。开始时,A中装满了水,B,C都为空。你的任务是,判断经过一系列操作后,能否使其中一个杯子里出现x升水。(一次操作指把x杯子里的水倒入y杯子中,因为杯子没有刻度 ,所以倒水时只允许将x杯子倒空,或将y杯子倒满。


输入:四个整数a,b,c,x.(1<=a<=b<=c<100,0<x<100)


输出:能的话,输出最短的操作步数,否则输出Impossible. 


样例:

6 3 1 4

10 8 7 5

输出:

3

impssbile

第一个样例所经过的步骤:(6,0,0)->(3,3,0)->(3,2,1)->(4,2,0) 

只有六种状态,BFS一下

a->b,a->c

b->a,b->c

c->a,c->b

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <queue>
 
using namespace std;
const double eps = 1e-6;
const int MAXN = 100010;
const double INF = 1e20;
int visit[101][101];
int aa[3];
int x;
struct Node
{
    int cap[3],step;
    Node(int x, int y,int z,int p)
    {
        cap[0] = x,cap[1] = y, cap[2] = z , step = p;
    }
    Node() {}
};
 
int BFS()
{
    memset(visit,0,sizeof(visit));
    queue<Node> Q;
    Q.push(Node(aa[0],0,0,0));
    visit[aa[0]][0] = 1;
    while(!Q.empty())
    {
        Node temp = Q.front(),temp2;
        Q.pop();
       if(temp.cap[0] == x || temp.cap[1] == x || temp.cap[2] == x) return temp.step;
 
        for(int i = 0; i < 3; i++)
        {
            for(int j = 0; j < 3; j++)
            {
                if(i == j) continue;
                int cha = aa[j] - temp.cap[j];
                temp2 = temp;
 
                if(temp2.cap[i] && cha )
                {
 
                    if(temp2.cap[i] > cha)
                    {
                        temp2.cap[j] = aa[j];
                        temp2.cap[i] -= cha;
                    }
                    else
                    {
                        temp2.cap[j] += temp2.cap[i];
                        temp2.cap[i] = 0;
 
                    }
 
                    if(!visit[temp2.cap[0]][temp2.cap[1]])
                    {
                        visit[temp2.cap[0]][temp2.cap[1]] = 1;
                        Q.push(Node(temp2.cap[0],temp2.cap[1],temp2.cap[2],temp2.step+1));
                    }
                }
 
            }
        }
    }
 
    return -1;
}
 
int main()
{
    #ifdef xxz
    freopen("in.txt","r",stdin);
    #endif // xxz
    while(~scanf("%d%d%d%d", &aa[0], &aa[1], &aa[2],&x))
    {
        int ans = BFS();
        if(ans == -1) printf("Impossible\n");
        else printf("%d\n",ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值