pots(BFS)

D - Pots
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Description

You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:

Input

 On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).

Output

 The first line of the output must contain the length of the sequence of operations K.  If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.

Sample Input

3 5 4

Sample Output

6

Hint

题意:两个水杯,已知体积A,B,经过三种转换方式达到C状态

1.清空水杯A/B

2.装满A/B

3.把A/B杯中的水倒入B/A中

简单BFS 题目的原型是POJ3414 简化

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int A, B, C;
int vis[105][105];
struct node
{
    int a, b, step;
};

void BFS()
{
    queue <node> q;
    int sa,sb;
    node f,t;
    f.a = 0; f.b = 0; f.step = 0;
    vis[f.a][f.b] = 1;
    q.push(f);
    while (!q.empty())
    {
        t = q.front();
        q.pop();
        if (t.a == C || t.b == C)
        {
            printf("%d\n",t.step);
            return ;
        }
        for (int i = 1; i <= 6; i++)
        {
            if (i == 1) //装满A
            {
                 sa = A;sb = t.b;
            }
            else if (i == 2)//装满B
            {
                 sa = t.a; sb = B;
            }
            else if (i == 3)//把B中水倒入A
            {
                if (t.a + t.b > A)
                    {sb = t.a + t.b - A;sa = A;}
                else
                    {sb = 0; sa = t.a + t.b;}
            }
            else if (i == 4)//把A中水倒入B
            {
                if (t.a + t.b > B)
                    {sa = t.a + t.b - B; sb = B;}
                else
                {
                    sa = 0; sb = t.a + t.b;
                }
            }
            else if (i == 5)//清空A
                {sa = 0; sb = t.b;}
            else
                {sa = t.a; sb = 0;}//清空B
            if (!vis[sa][sb])
            {
                vis[sa][sb] = 1;
                f.a = sa; f.b = sb;
                f.step = t.step + 1;
                q.push(f);
            }
        }
    }
    puts("impossible");
}

int main()
{
    while (scanf("%d%d%d", &A, &B, &C) != EOF)
    {
        memset(vis, 0, sizeof(vis));
        BFS();
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值