cdoj Egg Broken

E - Eggs broken

Time Limit: 5000/2000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)

There is a building which is n floors high. Bob has K same eggs now. It is known that, the egg will be broken if Bob throws it from the nth floor. Now Alice is wondering, what's the minimum expected times Bob will throw eggs until he finds the smallest x, if Bob throws an egg from the xth floor the egg will be broken.

The x is distributed in [1,n] uniformly.

As is known to everyone of you, Bob loves Alice very much. Could you tell Bob the answer to help Bob leave a good impression on Alice.

Input

The first line contains two integers n and K, which denote the number of floors and the number of eggs Bob has now.

It is guaranteed that 1n1000,1K15

Output

Print the minimum expected times Bob will throw eggs in one line.

The answer should be rounded to 5 digits after the decimal point.

Sample input and output

Sample Input Sample Output
4 2
2.00000


題意

有n層樓,k個蛋。已知從n摔下去蛋一定碎,0層摔下去一定不碎。你要找到一個x使蛋在第x層剛好摔碎(x-1不會碎)。然後這個x在[1,n]樓的分佈是均勻的。讓你求找到x(一定要找到x!)扔蛋次數的期望。

解析

概率dp。記憶化搜索。感覺每次二分地扔是最優解,事實上並不存在扔蛋最優策略,你只能1到n-1都試一下看那一次的期望最小。f(n,k)表示要有k個蛋來確定區間長爲n的樓層,扔蛋次數的期望是f(n,k)。順便說一句,在k相同的情況下,確定長爲L的區間扔蛋次數的期望總是一樣的,和樓層的高度沒關係,僅與區間長度有關。

轉移方程是f(n,k)=min(從i層摔碎了+從i層摔沒碎)=min( f(i,k-1)*(i/n)+f(n-i,k)*(1-i/n) )  (0<i<n) 

寫的時候犯了個愚蠢的錯誤,初始化ans=1……ans是期望不是概率,極大值不能設成1。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int N,K;
double dp[1010][16];

double f(int n,int k)//確定區間長度爲N的X,有k個蛋,返回的是扔的次數的期望
{
	if(dp[n][k]>0) return dp[n][k];
	if(n==1) return 0;
	if(k==0) return 0x3f3f3f3f;
	double ans=0x3f3f3f3f;
	for(int i=1;i<n;i++)//假設這次我從i扔下去
	{
		double p1=(double)i/n;//有p1的機率會爛
		double exception=f(i,k-1)*p1//爛了,然後下樓
						+f(n-i,k)*(1-p1);//沒爛,上樓
		ans=min(ans,exception);
	}
	//printf("f(%d,%d)=%.5f\n",n,k,ans+1);
	return dp[n][k]=ans+1;
}

int main()
{
	memset(dp,0,sizeof(dp));
	scanf("%d%d",&N,&K);
	printf("%.5lf\n",f(N,K));
	return 0;
}


發佈了123 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章