Edward is the headmaster of Marjar University. He is enthusiastic about chess and often plays chess with his friends. What's more, he bought a large decorative chessboard with Nrows and M columns.
Every day after work, Edward will place a chess piece on a random empty cell. A few days later, he found the chessboard was dominated by the chess pieces. That means there is at least one chess piece in every row. Also, there is at least one chess piece in every column.
"That's interesting!" Edward said. He wants to know the expectation number of days to make an empty chessboard of N × M dominated. Please write a program to help him.
Input
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
There are only two integers N and M (1 <= N, M <= 50).
Output
For each test case, output the expectation number of days.
Any solution with a relative or absolute error of at most 10sup>-8 will be accepted.
Sample Input
2 1 3 2 2
Sample Output
3.0000000000002.666666666667
题意:一个n*m的棋盘,要往棋盘里放棋子,最终要使每行每列至少有一枚棋子,问放棋子个数的期望
E=Σp(i)*i;
如何求p(i)呢,想到递推公式,dp[i][j][k],表示在i*j的子棋盘中放了k个棋子的概率
dp[i][j][k]=dp[i][j][k-1]*(p1)+dp[i-1][j][k-1]*(p2)+dp[i][j-1][k-1]*(p3)+dp[i-1][j-1][k-1]*(p4);
其中p1 p2 p3 p4 表示将要选择的一个区域的概率 ,=将要选择区域格子/剩余格子数
ac代码,有详解:
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; double dp[55][55][2550]; int main() { int n,m; int t; cin>>t; while(t--) { cin>>n>>m; int sum=n*m; memset(dp,0,sizeof(dp)); dp[0][0][0]=1.0;///用0个棋子铺满0*0的棋盘概率为1 for(int k=1;k<=sum;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { double fm=1.0*(sum-k+1);///fm 表示分母,即剩余的格子数sum-(k-1) dp[i][j][k]+=dp[i][j][k-1]* (i*j-k+1) *1.0/fm;///在i*j-(k-1)个位置中任意选一个格子的概率 dp[i][j][k]+=dp[i-1][j][k-1]* (n-i+1)*j *1.0/fm;///在(n-(i-1))*j个位置中选一个位置的概率 dp[i][j][k]+=dp[i][j-1][k-1]* (m-j+1)*i *1.0/fm;///在(m-(j-1))*i个位置中选一个位置的概率 dp[i][j][k]+=dp[i-1][j-1][k-1]* (m-j+1)*(n-i+1) *1.0/fm;///在(n-(i-1))*(m-(j-1))个位置中选一个位置的概率 /**dp[i][j][k]= dp[i-1][j-1][k-1]* (m-j+1)*(n-i+1) *1.0/fm+dp[i][j-1][k-1]* (m-j+1)*i *1.0/fm +dp[i-1][j][k-1]* (n-i+1)*j *1.0/fm+dp[i][j][k-1]* (i*j-k+1) *1.0/fm; */ } } } double ans=0; for(int k=1;k<=sum;k++) { ans+=(dp[n][m][k]-dp[n][m][k-1])*k;///dp[i][j][k]-dp[i][j][k-1]得到是第k个棋子恰好使得每行每 ///列都占领的概率,排除k-1个棋子完成目标概率 printf("%d %.5lf %.5lf\n",k,dp[n][m][k],dp[n][m][k]-dp[n][m][k-1]); } printf("%.10lf\n",ans); } return 0; } /** 3 3 3 放k个棋子 放k个棋子 可以完成目标 的概率 的概率 1 0.00000 0.00000 2 0.00000 0.00000 3 0.07143 0.07143 4 0.35714 0.28571 5 0.71429 0.35714 6 0.92857 0.21429 7 1.00000 0.07143 8 1.00000 0.00000 9 1.00000 0.00000 4.9285714286 */