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[i][j][k] 代表放了k个棋子占了i行j列 到达目标状态的期望
对于 dp[i][j][k+1] 其实就是剩下的空再放一个,概率就是(j*k-i) / (n*m-i)
对于 dp[i+1][j][k+1] 就是剩下的行乘上现有的列找一个放,概率就是 ((n-j)*k)/(n*m-i)
对于dp[i][j+1][k+1]就是剩下的列乘上现有的行找一个放 ,概率就是 ((m-k)*j)/(n*m-i)
最后 dp[i+1][j+1][k+1] 就是剩下的行乘上剩下的列找一个放 ,概率就是(n-j)*(m-k))/(n*m-i)
#include<iostream> #include<string> #include<algorithm> #include<cstdlib> #include<cstdio> #include<set> #include<map> #include<vector> #include<cstring> #include<stack> #include<cmath> #include<queue> using namespace std; double dp[55][55][2505]; int main() { int i,j,k,l,m,n,t; double ans; scanf("%d",&t); while(t--) { ans=0; scanf("%d%d",&n,&m); memset(dp,0,sizeof(dp)); dp[1][1][1]=1; l=m*n; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { for(k=0;k<=n*m;k++) { dp[i][j][k+1]+=dp[i][j][k]*(i*j-k)*1.0/(l-k); dp[i+1][j][k+1]+=dp[i][j][k]*(n-i)*j*1.0/(l-k); dp[i][j+1][k+1]+=dp[i][j][k]*(m-j)*i*1.0/(l-k); dp[i+1][j+1][k+1]+=dp[i][j][k]*(n-i)*(m-j)*1.0/(l-k); } } } for(i=max(n,m);i<=l;i++) { ans+=(dp[n][m][i]-dp[n][m][i-1])*i; } printf("%.8lf\n",ans); } }