Description
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 dominatedby 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
题意:
一个n行m列的棋盘,每次可以放一个棋子,问要使得棋盘的每行每列都至少有一个棋子 需要的放棋子次数的期望。
那么对于每一颗棋子,在现有的棋盘上,它可能有四种影响:新占了一行,新占了一列,既占了新的一行又占了新的一列,无影响。
注意这里的无影响指的不是下在同一个位置,这是不允许的,指的是已有(1,2),(2,1),下在(1,1)无影响,不增加行和列。
题解一:
dp[i][j][k] 已经占据i行j列,走了k步的时候,还需要走的步数的期望。
#include<cstdio> #include<cstring> #include<iostream> using namespace std; double dp[55][55][55*55]; int main() { int t; scanf("%d",&t); while(t--) { int n,m; scanf("%d%d",&n,&m); memset(dp,0,sizeof(dp)); for(int i=n;i>=0;i--) for(int j=m;j>=0;j--) for(int k=i*j;k>=max(i,j);k--) { if(i==n&&j==m) continue; dp[i][j][k]+=1.0*(n-i)*j/(1.0*n*m-k)*dp[i+1][j][k+1]; dp[i][j][k]+=1.0*i*(m-j)/(1.0*n*m-k)*dp[i][j+1][k+1]; dp[i][j][k]+=1.0*(n-i)*(m-j)/(1.0*n*m-k)*dp[i+1][j+1][k+1]; dp[i][j][k]+=1.0*(i*j-k)/(1.0*n*m-k)*dp[i][j][k+1]; dp[i][j][k]+=1.0; } printf("%.12lf ",dp[0][0][0]); } }
题解二:
dp[i][j][k]表示用了k个棋子共能占领棋盘的i行j列的概率。
所以用dp[i][j][k]-dp[i][j][k-1]得到是第k个棋子恰好使得每行每列都占领的概率。
#include<cstdio> #include<cstring> double dp[55][55][2550]; int n,m; int main() { int T,i,j,k; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); int sum=n*m; for(i=0;i<=n;i++) for(j=0;j<=m;j++) for(k=0;k<=sum;k++) dp[i][j][k]=0; dp[0][0][0]=1.0; for(k=1;k<=sum;k++) for(i=1;i<=n;i++) for(j=1;j<=m;j++) { dp[i][j][k]+=(dp[i][j][k-1]*(i*j-k+1)*1.0/(sum-k+1));//添加的位置没有新增新行或新列 dp[i][j][k]+=(dp[i-1][j][k-1]*((n-i+1)*j)*1.0/(sum-k+1));//增加行不增加列 dp[i][j][k]+=(dp[i][j-1][k-1]*(m-j+1)*i*1.0/(sum-k+1));//增加列不增加行 dp[i][j][k]+=(dp[i-1][j-1][k-1]*(n-i+1)*(m-j+1)*1.0/(sum-k+1));//既增加列也增加行 // printf("i:%d j;%d k;%d dp:%lf ",i,j,k,dp[i][j][k]); } double ans=0; for(k=1;k<=sum;k++) ans+=(dp[n][m][k]-dp[n][m][k-1])*k; printf("%.10lf ",ans); } return 0; }