ZOJ3582:Back to the Past(概率DP)

Recently poet Mr. po encountered a serious problem, rumor said some of his early poems are written by others. This brought a lot of trouble to Mr. po, so one day he went to his best friend MasterO for help. MasterO handed over a small wooden box with a silent smile. Mr. po checked the box, a word "YGBH" carved on the side. "The box can take you back to the past," MasterO said, "so you can get any evidence you need. But, before that, you need some patience."

There are N tiny dark holes on both sides of the box (2N holes in total). Every day, for each hole, there is a possibility P to successfully absorb the power of moon and then magically sparkle. The possibilities among holes are independent in each day. Once a hole sparkles, it will never turn dark again. The box only works when there are no less than M sparkling holes on each side of the box. The question is that what is the expected number of days before the box is available.

Input

The input consists of several test cases. For each case there are 3 numbers in a line: NMP. 1 ≤ N ≤ 50, 1 ≤ M ≤ N, 0.01 ≤ P ≤ 1. A case with three zeros indicates the end of the input.

Output

For each test case, output the expected number of days, accurate up to six decimal places.

Sample Input

2 1 1
1 1 0.5
0 0 0

Sample Output

1.000000
2.666667
 
题意:给出n,m,p,盒子两边各有n盏灯,要求两边都至少亮m盏灯的期望,每个灯的亮暗都是独立的,亮的概率为p,亮了的灯不会再熄灭
思路:又是一道概率DP求期望的问题,设dp[i][j]表示左边i个亮,右边j个亮到达目标的期望
则dp[i][j]=1+sigma{C(n-i,x)*p^x*(1-p)^(n-i-x) * C(n-j,y)*p^y*(1-p)^(n-j-y)*dp[i+x][j+y]};
注意这里的C(n-i,x)是一个组合数,这些组合数可以用杨辉三角的性质对它们进行打表处理
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std; double dp[55][55],c[55][55];
double yes[55],no[55];
//dp[i][j]表示一边亮i个洞,一边亮j个洞到达成目标还需的天数
void set()//杨辉三角打表,也就是二项式各项系数
{
int i,j;
for(i = 0; i<=55; i++)
{
c[i][0] = c[i][i] = 1;
for(j = 1; j<i; j++)
c[i][j] = c[i-1][j-1]+c[i-1][j];
}
} int main()
{
int n,m,i,j,x,y;
double p,sum;
set();
while(~scanf("%d%d%lf",&n,&m,&p))
{
if(n==0 && m==0)
break;
yes[0] = no[0] = 1;
for(i = 1; i<=n; i++)
{
yes[i] = yes[i-1]*p;
no[i] = no[i-1]*(1.0-p);
}
memset(dp,0,sizeof(dp));
for(i = n; i>=0; i--)
{
for(j = n; j>=0; j--)
{
//i,j,代表左右已亮的个数
if(i>=m && j>=m)
continue;
sum = 0;
for(x = 0; x+i<=n; x++)
{
for(y = 0; y+j<=n; y++)
{
if(x==0 && y==0)
continue;
if(n-i>=x && n-j>=y)
sum+=dp[x+i][y+j]*c[n-i][x]*yes[x]*no[n-i-x]*c[n-j][y]*yes[y]*no[n-j-y];
//x,y是左右新增的亮起来的个数
//c[n-i][x],就是在剩下的n-i个中选x个作为新亮起来的灯,也就是一个组合数
}
}
dp[i][j] = (sum+1.0)/(1.0-no[n-i]*no[n-j]);//求期望,+1是一天过了,除以(1.0-no[n-i]*no[n-j])是至少亮了一盏
}
}
printf("%.6f\n",dp[0][0]);
} return 0;
}
上一篇:解决:导入第三方jar包后,仍然出现java.lang.NoClassDefFoundError的错误


下一篇:Python之路,Day1 - Python基础1 介绍、基本语法、流程控制