Balls POJ - 3783(鹰蛋问题,DP)

The classic Two Glass Balls brain-teaser is often posed as:

“Given two identical glass spheres, you would like to determine the lowest floor in a 100-story building from which they will break when dropped. Assume the spheres are undamaged when dropped below this point. What is the strategy that will minimize the worst-case scenario for number of drops?”

Suppose that we had only one ball. We’d have to drop from each floor from 1 to 100 in sequence, requiring 100 drops in the worst case.

Now consider the case where we have two balls. Suppose we drop the first ball from floor n. If it breaks we’re in the case where we have one ball remaining and we need to drop from floors 1 to n-1 in sequence, yielding n drops in the worst case (the first ball is dropped once, the second at most n-1 times). However, if it does not break when dropped from floor n, we have reduced the problem to dropping from floors n+1 to 100. In either case we must keep in mind that we’ve already used one drop. So the minimum number of drops, in the worst case, is the minimum over all n.

You will write a program to determine the minimum number of drops required, in the worst case, given B balls and an M-story building.
Input
The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set consists of a single line containing three(3) decimal integer values: the problem number, followed by a space, followed by the number of balls B, (1 ≤ B ≤ 50), followed by a space and the number of floors in the building M, (1 ≤ M ≤ 1000).
Output
For each data set, generate one line of output with the following values: The data set number as a decimal integer, a space, and the minimum number of drops needed for the corresponding values of B and M.
Sample Input
4
1 2 10
2 2 100
3 2 300
4 25 900
Sample Output
1 4
2 14
3 24
4 10

题意: n个蛋,m层楼。到了某层楼之下的的所有楼,扔蛋都不会碎,之上的所有楼扔蛋都会碎。问你最坏情况下,最少扔几次会确认出这层楼

思路:
很经典的问题了,求的是最大值的最小,而且楼层具有单调性,一般会想到二分。
正解是DP,状态定义还是很明显的了(看了题解就明显了。。。)
定义状态为F[i][j]代表i个蛋j层楼的最小试验次数。
第K层楼扔的时候:
如果碎了,那么结果是F[i-1][k-1]+1。
没碎,结果是F[i][j-k]+1.
转移的时候就是去最大值的最小:
F[i][j] = min(F[i][j],max(F[i-1][k-1],F[i][j-k])+1).

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int f[55][1005];
int main()
{
    int T;scanf("%d",&T);
    int cas;
    while(T--)
    {
        int n,m;scanf("%d%d%d",&cas,&n,&m);
        
        memset(f,0x3f,sizeof(f));
        for(int i = 1;i <= m;i++)f[1][i] = i;
        for(int i = 1;i <= n;i++)f[i][0] = 0;
        
        for(int i = 1;i <= n;i++)
        {
            for(int j = 1;j <= m;j++)
            {
                for(int k = 1;k <= j;k++)
                {
                    f[i][j] = min(f[i][j],max(f[i - 1][k - 1],f[i][j - k]) + 1);
                }
            }
        }
        
        printf("%d %d\n",cas,f[n][m]);
    }
    return 0;
}

发布了676 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104215284