您的位置:首页 > 其它

【POJ3783 Ball】 动态规划

2011-03-20 16:55 399 查看
题意:

有m个相同的玻璃球,n层楼,你想知道这些玻璃球从第几层往下落的时候会摔烂。

最坏情况下最少需要扔多少次玻璃球才能测出玻璃球的强度?

如果还不太明了题意,就看我从别的网页上转来的一段,讲的是最基本的两个玻璃球的情况:

google面试题 谁知道一定能测出那层的最低次数?
5
Google Interview Puzzle : 2 Egg Problem
* You are given 2 eggs.
* You have access to a 100-story building.
* Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100th floor. Both eggs are identical.
* You need to figure out the highest floor of a 100-story building an egg can be dropped without breaking.
* Now the question is how many drops you need to make. You are allowed to break 2 eggs in the process
满意答案
好评率:0%
如果第一个蛋破裂在最高点我们要扔x-1次并且我们必须从x层高扔第一个蛋。现在如果第一个蛋的第一次扔没有破裂,如果第一个蛋在第二次扔破了我们要扔x-2次第二个蛋。假如16是答案,我需要扔16次才能找到答案。来验证一下是否可以从16层开始扔,首先从16层扔如果它破裂了,我们尝试所有其下的楼层从1到15;如果没破我们还能扔15次,于是我们将从32层(16+15+1)再扔。原因是如果它在32层破裂我们能尝试其下所有楼层从17到31最坏扔第二个蛋14次(总共能扔16次了)。如果32层并没破,我们还剩下能扔13次,依此类推得:
1 + 15 16 如果它在16层破裂,从1到15层最坏扔15次第二个蛋
1 + 14 31 如果它在31层破裂,从17到30层最坏扔14次第二个蛋
1 + 13 45.....
1 + 12 58
1 + 11 70
1 + 10 81
1 + 9  91
1 + 8  100 在最后我们能轻易地做到因为我们有足够多扔的次数来完成任务
从上表我们能看到最佳的一个在最后一步将需要0次线性搜索。
能把上述规律写为: (1+p) + (1+(p-1))+ (1+(p-2)) + .........+ (1+0) >= 100.
令1+p=q上述式子变为q(q+1)/2>=100,对100解答得到q=14。
扔第一个蛋从层14,27,39,50,60,69,77,84,90,95,99,100直到它破裂,再开始扔第二个蛋。最坏情况只需14次。

#include<iostream>
#include<algorithm>
using namespace std;
const int MAXBall=55,MAXFloor=1010;
int DP[MAXBall][MAXFloor];
int main()
{
for(int i=0;i<=1000;i++) DP[1][i]=i;
for(int i=2;i<=50;i++)
for(int j=1;j<=1000;j++)
{
if(i>j) DP[i][j]=DP[j][j];
else DP[i][j]=DP[i-1][j-1]+DP[i][j-1]+1;
if(DP[i][j]>1010) DP[i][j]=1010;
}
int n,th,ball,floor;
cin>>n;
while(n--)
{
cin>>th>>ball>>floor;
cout<<th<<" "<<lower_bound(DP[ball],DP[ball]+1000,floor)-DP[ball]<<endl;
}
}


DP[m]
表示m个球,n次机会,最多能在多少层楼的情况下检测出。
则
if(i>j) DP[i][j]=DP[j][j];
else DP[i][j]=DP[i-1][j-1]+DP[i][j-1]+1;

最后二分DP[ballnum]数组即可。
不过要注意中间可能DP的值超大,所以在上面两行之后加上一句:
if(DP[i][j]>1010) DP[i][j]=1010;
防止超范围
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: