算法题 Jugs

Jugs by Stack from ZOJ(浙大OJ) Problem Set - 1005,链接http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1005

题目如下:

 In the movie "Die Hard 3", Bruce Willis and Samuel L. Jackson were confronted with the following puzzle. They were given a 3-gallon jug and a 5-gallon jug and were asked to fill the 5-gallon jug with exactly 4 gallons. This problem generalizes that puzzle.

You have two jugs, A and B, and an infinite supply of water. There are three types of actions that you can use: (1) you can fill a jug, (2) you can empty a jug, and (3) you can pour from one jug to the other. Pouring from one jug to the other stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons and B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A.

A problem is given by a triple (Ca,Cb,N), where Ca and Cb are the capacities of the jugs A and B, respectively, and N is the goal. A solution is a sequence of steps that leaves exactly N gallons in jug B. The possible steps are

fill A
fill B
empty A
empty B
pour A B
pour B A
success

where "pour A B" means "pour the contents of jug A into jug B", and "success" means that the goal has been accomplished.

You may assume that the input you are given does have a solution.

Input

Input to your program consists of a series of input lines each defining one puzzle. Input for each puzzle is a single line of three positive integers: Ca, Cb, and N. Ca and Cb are the capacities of jugs A and B, and N is the goal. You can assume 0 < Ca <= Cb and N <= Cb <=1000 and that A and B are relatively prime to one another.

Output

Output from your program will consist of a series of instructions from the list of the potential output lines which will result in either of the jugs containing exactly N gallons of water. The last line of output for each puzzle should be the line "success". Output lines start in column 1 and there should be no empty lines nor any trailing spaces.

Sample Input

3 5 4
5 7 3

Sample Output

fill B
pour B A
empty A
pour B A
fill B
pour B A
success
fill A
pour A B
fill A
pour A B
empty B
pour A B
success

题目简述:

有无限的水和两个水桶,一个容量 A升,一个容量 B升,问怎么用两个桶得到 n升水。

我的思路:

刚开始看到这道题目,还是有点措手不及,然后思考一阵子之后,就想到了用深度优先遍历把所有的情况都遍历一遍,大致思路是这样的:

每一层表示A和B的一个状态,函数的con专门用来储存状态,behavior用来储存做了什么操作,进入下一层的时候会先判断现在的状态是否在以前出现过,如果出现过则返回(不判断的会无限递归),然后在进行一系列pour,empty,fill操作,on用来表示程序是否继续执行,当B的值等于n的时候,则on标记为0表示退出,退出之前会打印做的行为。

我的代码:

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

#define NONE 0
#define POUR_A_TO_B 1
#define POUR_B_TO_A 2
#define FILL_A 3
#define FILL_B 4
#define EMPTY_A 5
#define EMPTY_B 6

typedef struct
{
    short A;
    short B;
} jug;

void print(char *behavior, int length)
{
    int i;
    for (i = 0; i < length; i++)
    {
        switch (behavior[i])
        {
        case POUR_A_TO_B:
            puts("pour A B");
            break;

        case POUR_B_TO_A:
            puts("pour B A");
            break;

        case FILL_A:
            puts("fill A");
            break;

        case FILL_B:
            puts("fill B");
            break;

        case EMPTY_A:
            puts("empty A");
            break;

        case EMPTY_B:
            puts("empty B");
            break;

        default:
            fprintf(stderr, "Error\n");
            exit(-1);
            break;
        }
    }

    puts("success");
}

void dfs(int *on, jug *con, int *con_length, char *behavior, int behavior_length, jug max, int now_a, int now_b, int n)
{
    int i, temp;
    // 判断是否完成
    if (!*on)
    {
        return;
    }
    // 如果重复了以前的状态,则返回
    for (i = 0; i < *con_length; i++)
    {
        if (now_a == con[i].A && now_b == con[i].B)
        {
            return;
        }
    }
    if (now_b == n)
    {
        print(behavior, behavior_length);
        *on = 0;
        return;
    }

    // 增加新状态
    con[*con_length].A = now_a;
    con[*con_length].B = now_b;
    (*con_length)++;

    if (now_a > 0 && now_b < max.B)
    {
        behavior[behavior_length] = POUR_A_TO_B;
        temp = max.B - now_b;
        if (temp > now_a)
        {
            dfs(on, con, con_length, behavior, behavior_length + 1, max, 0, now_a + now_b, n);
        }
        else
        {
            dfs(on, con, con_length, behavior, behavior_length + 1, max, now_a - temp, now_b + temp, n);
        }
    }

    if (now_b > 0 && now_a < max.A)
    {
        behavior[behavior_length] = POUR_B_TO_A;
        temp = max.A - now_a;
        if (temp > now_b)
        {
            dfs(on, con, con_length, behavior, behavior_length + 1, max, now_a + now_b, 0, n);
        }
        else
        {
            dfs(on, con, con_length, behavior, behavior_length + 1, max, now_a + temp, now_b - temp, n);
        }
    }

    if (now_a > 0)
    {
        behavior[behavior_length] = EMPTY_A;
        dfs(on, con, con_length, behavior, behavior_length + 1, max, 0, now_b, n);
    }

    if (now_b > 0)
    {
        behavior[behavior_length] = EMPTY_B;
        dfs(on, con, con_length, behavior, behavior_length + 1, max, now_a, 0, n);
    }

    if (now_a < max.A)
    {
        behavior[behavior_length] = FILL_A;
        dfs(on, con, con_length, behavior, behavior_length + 1, max, max.A, now_b, n);
    }

    if (now_b < max.B)
    {
        behavior[behavior_length] = FILL_B;
        dfs(on, con, con_length, behavior, behavior_length + 1, max, now_a, max.B, n);
    }

    behavior[behavior_length] = NONE;
}

int main()
{
    int n, on, con_length;
    char behavior[0x10000];
    jug con[0x10000], max;
    while (scanf("%hd %hd %d", &max.A, &max.B, &n) != EOF)
    {
        con_length = 0;
        on = 1;
        dfs(&on, con, &con_length, behavior, 0, max, 0, 0, n);
    }
    return 0;
}

执行效果如下:

3 5 4
5 7 3
fill A
pour A B
fill A
pour A B
empty A
pour B A
empty A
pour B A
fill B
pour B A
success
fill A
pour A B
fill A
pour A B
empty A
pour B A
empty A
pour B A
fill B
pour B A
empty A
pour B A
fill B
pour B A
empty A
pour B A
empty A
pour B A
fill B
pour B A
success

虽然和给定的输出有差别,但是提交是可以过的,毕竟条条大路通罗马。

比较:

这里我引用的是 “成鹏致远” 博客(http://infohacker.blog.51cto.com/6751239/1230301)的代码,相比较这位大佬的代码,我的代码是比较冗余的,而且大佬用的是循环,我用的是深度优先遍历(递归),速度上差距很大,而且我设计的也比较耗内存,这位大佬的代码确实值得我好好学习。

这位大佬的思路是:不断进行多轮循环测试,单轮循环开始时给A注满水,先进行pour操作,而每一轮循环表示多个pour操作,直到A或者B为满或者空时,才结束本轮循环,进入下一次循环测试,直到B为n时才结束循环。

大佬的代码:

#include <stdio.h>
int main()
{
    int ca, cb, n, x, y;
    /* Ca, Cb, and N. Ca and Cb are the capacities of jugs A and B, and N is the goal.
     * 即:ca为 A的容量,cb为 B的容量,N为要得到的水
     * x为 ca当前已有的水
     * y为 cb当前已有的水
     */
    while (scanf("%d %d %d", &ca, &cb, &n) != EOF)
    {
        x = y = 0;
        while (1)
        {
            printf("fill A\n");
            x = ca;
            if (x == n) /* 如果 A得到目标 */
            {
                printf("success\n");
                break; /* 成功,退出循环 */
            }
            while (x > 0)
            {
                if ((cb - y) >= x) /* B能够容纳的水 > A当前的水 */
                {
                    printf("pour A B\n"); /* 则将 A中的水全部倒入 B中 */
                    y = y + x;            /* y增加 x升水 */
                    x = 0;
                }
                else
                {
                    printf("pour A B\n");
                    x = x - (cb - y); /* A中还剩有水 */
                    y = cb;           /* B中装满 */
                }
                if (x == n) /* A得到目标 */
                {
                    printf("success\n");
                    break;
                }
                if (y == n) /* B得到目标 */
                    break;
                if (y == cb) /* B空 */
                {
                    printf("empty B\n");
                    y = 0;
                }
            }
            if (x == n)
                break;
            if (y == n)
            {
                printf("success\n");
                break;
            }
        }
    }
    return 0;
}

说点什么

avatar
  Subscribe  
提醒