Recently one of my friend Tarik became a member of the food committee of an ACM regional competition. He has been given m distinguishable boxes, he has to put n types of chocolates in the boxes. The probability that one chocolate is placed in a certain box is 1/m. What is the probability that one or more boxes are empty? At first he thought it as an easy task. But soon he found that it was much harder. So, he falls into a great trouble and asked you to help him in this task. Input Each line of the input contains two integers n indicating total number of distinguishable types of chocolate and m indicating total number of distinguishable boxes (m ≤ n < 100). A single line containing ‘-1’ denotes the end. Output For each of the cases you should calculate the probability corrected to seven decimal places. The output format is shown below.
Sample Input
50 12
50 12
-1
Sample Output
Case 1: 0.1476651
Case 2: 0.1476651
思路:题目要求一个或者 多个盒子为空的概率,可以先求所有盒子都不为空的概率;
设dp[i][j]为i个巧克力放入j个盒子的概率;
分为两种情况:1)前i-1个巧克力放入了j个盒子:则第i个就放入前j个盒子;
2)前i-1个巧克力放入了j-1个盒子:则第i个就放入剩下的m-(j-1)个盒子;
状态转移公式为:dp[i][j]=dp[i-1][j]*f[j]+dp[i-1][j-1]*f[m-j+1];
f[i]为i/m;
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstdlib> 6 #include<iomanip> 7 #include<cmath> 8 #include<vector> 9 #include<queue> 10 #include<stack> 11 using namespace std; 12 #define PI 3.141592653589792128462643383279502 13 double dp[105][105]; 14 int i,j,k,n,m; 15 double f[106]; 16 int main(){ 17 //#ifdef CDZSC_June 18 // freopen("in.txt","r",stdin); 19 //#endif 20 //std::ios::sync_with_stdio(false); 21 k=0; 22 while(cin>>n){ 23 if(n==-1) break; 24 cin>>m; 25 memset(dp,0,sizeof(dp)); 26 for(i=1;i<=m;i++) f[i]=(double)i/m; 27 dp[1][1]=1; 28 for(i=2;i<=n;i++) 29 for(j=1;j<=m;j++){ 30 dp[i][j]=dp[i-1][j]*f[j]+dp[i-1][j-1]*f[m-j+1]; 31 } 32 printf("Case %d: %.7lf\n",++k,1-dp[n][m]); 33 } 34 return 0; 35 }