如何以编程方式解决2个玻璃球拼图?

时间:2012-01-23 11:52:35

标签: algorithm puzzle

有一个受欢迎的puzzle大约100层的建筑物和两个玻璃球。我看到了解决方案,现在我想知道我是否可以通过编程方式解决难题

简单的程序化解决方案是一个完整的搜索(我相信我可以使用回溯编码)。有没有更好的程序化解决方案?我可以使用动态编程来解决难题吗?

2 个答案:

答案 0 :(得分:5)

这类似于掉蛋拼图。我将在动态编程中为您提供基本策略。与您的问题密切相关。

# include <stdio.h>
# include <limits.h>

// A utility function to get maximum of two integers
int max(int a, int b) { return (a > b)? a: b; }

/* Function to get minimum number of trails needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
/* A 2D table where entery eggFloor[i][j] will represent minimum
   number of trials needed for i eggs and j floors. */
int eggFloor[n+1][k+1];
int res;
int i, j, x;

// We need one trial for one floor and0 trials for 0 floors
for (i = 1; i <= n; i++)
{
    eggFloor[i][1] = 1;
    eggFloor[i][0] = 0;
}

// We always need j trials for one egg and j floors.
for (j = 1; j <= k; j++)
    eggFloor[1][j] = j;

// Fill rest of the entries in table using optimal substructure
// property
for (i = 2; i <= n; i++)
{
    for (j = 2; j <= k; j++)
    {
        eggFloor[i][j] = INT_MAX;
        for (x = 1; x <= j; x++)
        {
            res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
            if (res < eggFloor[i][j])
                eggFloor[i][j] = res;
        }
    }
}

// eggFloor[n][k] holds the result
return eggFloor[n][k];
}

/* Driver program to test to pront printDups*/
int main()
{
    int n = 2, k = 36;
    printf ("\nMinimum number of trials in worst case with %d eggs and %d floors is %d \n", n, k, eggDrop(n, k));
    return 0;
}
  

<强>输出:   在最坏的情况下,2个鸡蛋和36个楼层的最低试验次数是8

答案 1 :(得分:0)

我很抱歉,但之前的回答对这个问题不公平。最好的时间是N的sqrt。有人会尝试用logn反驳这个,但很抱歉,事实并非如此。

// my prentend breaking function
function itBreaks(level) {
    return level > 36;
}

function search(maxLevel) {
    var sqrtN = Math.floor(Math.sqrt(maxLevel));
    var i = 0;
    for (;i < maxLevel; i += sqrtN) {
        if (itBreaks(i)) {
            break;
        }
    }

    for (i -= sqrtN; i < maxLevel; i++) {
        if (itBreaks(i)) {
            return i - 1;
        }
    }
}