ZOJ 3822
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 N rows 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 10-8 will be accepted.
Sample Input
2
1 3
2 2
Sample Output
3.000000000000 2.666666666667
一开始以为是搜索,枚举每一天能满足条件的数目,后面就能算出概率= =。然后再求期望,结果第二个样例就算不出来。
看别人说就是个概率DP。
状态d[k][i][j]:第i天,覆盖了i行j列的概率。
#include <cstdio> #include <cstring> #include <queue> using namespace std; #define N 55 int t,m,n; double d[N*N][N][N]; int main(){ int T; scanf("%d", &T); while(T--){ scanf("%d %d", &n, &m); memset(d,0,sizeof(d)); double ans = 0; d[0][0][0] = 1; for(int k = 1; k <= n*m; k++){ double sum = n*m-k+1; for(int i = 1; i <= k && i <= n; i++) for(int j = 1; j <= k && j <= m; j++){ double f1 = (double)(n-i+1)*j/sum; double f2 = (double)i*(m-j+1)/sum; double f3 = (double)(n-i+1)*(m-j+1)/sum; double f4 = (double)(i*j - k+1)/sum; if(i != n || j != m) d[k][i][j] = d[k-1][i-1][j]*f1 + d[k-1][i][j-1]*f2 + d[k-1][i-1][j-1]*f3 + d[k-1][i][j]*f4; else d[k][i][j] = d[k-1][i-1][j]*f1 + d[k-1][i][j-1]*f2 + d[k-1][i-1][j-1]*f3; } ans +=(double)k*d[k][n][m]; } printf("%.12lf\n", ans); } return 0; }