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.0000000000002.666666666667
题意:有一个N*M的棋盘,每天会在棋盘的所有未放棋子的格子中随机选择一个位置放置一个棋子,问棋盘要达到每行行列最少有一个棋子,平均需要放多少枚棋子。
思路:我们用dp[i][j][k] 表示已经放了i个棋子,有j行有棋子,有k列有棋子的概率。
注意其实选棋子就相当于选一个(r,c)的二元组。
我们能得到转移:dp[i+1][j][k] += dp[i][j][k] * (j * k - i) / (N * M - i); (j * k - i >= 0)
意义:表示新选的棋子的行号和列号都已经选过了
dp[i+1][j+1][k] += dp[i][j][k] * (N-j) * k / ( N * M - i);
意义:表示新选的棋子的行号没选过,但是列号选过了。
dp[i+1][j][k+1] += dp[i][j][k] * j * (N - k) / (N*M - i);
意义:表示新选的棋子的行号已经选过,但是列号没被选过。
dp[i+1][j+1][k+1] += dp[i][j][k] * (N - j) * (M - k) / (N * M - i);
意义:表示新选的棋子的行号和列号均为被选过。
注意dp[i][N][M]不能进行转移,因为要求达到之后就不会再放棋子了。
最后我们的答案就是 sigma ( i * dp[i][N][M]) ( 1<=i<=N*M)
代码:
#include <iostream> #include <string.h> #include <cstring> #include <stdio.h> #define rep(i,a,b) for(int i=(a);i<(b);++i) #define rrep(i,b,a) for(int i = (b); i >= (a); --i) #define clr(a,x) memset(a,(x),sizeof(a)) using namespace std; const int maxn = 50 + 5; double dp[maxn*maxn][maxn][maxn]; int main() { int T; cin >> T; while (T--) { int N, M; scanf("%d%d", &N, &M); clr(dp, 0); dp[0][0][0] = 1.0; rep(i, 0, N*M) rep(j, 0, N + 1) rep(k, 0, M + 1) { if (j == N && k == M || dp[i][j][k] == 0) continue; if (j * k >= i) dp[i + 1][j][k] += dp[i][j][k] * (j*k - i) / (N*M - i); if (j + 1 <= N) dp[i + 1][j + 1][k] += dp[i][j][k] * (N - j) * k / (N*M - i); if (k + 1 <= M) dp[i + 1][j][k + 1] += dp[i][j][k] * j * (M - k) / (N*M - i); if (j + 1 <= N && k + 1 <= M) dp[i + 1][j + 1][k + 1] += dp[i][j][k] * (N - j) *(M - k) / (N*M - i); } double ans = 0; rep(i, 0, N*M+1) ans += i * dp[i][N][M]; printf("%.10lf\n", ans); } }