zoj3822(概率dp)
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 wasdominated 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 × Mdominated. 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的棋盘上放一颗棋子,求平均多少天能将棋盘的每行每列都至少有一颗棋子。
思路:先求概率再求期望。求概率的过程用dp[i][j][k]表示放i个棋子的棋盘上已经有j行有棋子k列有棋子的概率。至于状态转移的过程,见下图:
图中红色部分可视为j行k列已经至少有一个棋子了,然后进行状态转移的时候看这个图理解足矣!
#include <iostream> #include <stdio.h> #include <stdlib.h> #include<string.h> #include<algorithm> #include<math.h> #include<queue> #include<iomanip> using namespace std; typedef long long ll; double dp[2510][50][50]; int main() { int t; scanf("%d",&t); while(t--) { memset(dp,0,sizeof(dp)); int n,m; scanf("%d%d",&n,&m); dp[1][1][1]=1; for(int i=1; i<m*n; i++) for(int j=1; j<=n; j++) for(int k=1; k<=m; k++) if(dp[i][j][k]) { dp[i+1][j+1][k]+=dp[i][j][k]*(n-j)*k/(double)(m*n-i); dp[i+1][j][k+1]+=dp[i][j][k]*(m-k)*j/(double)(m*n-i); dp[i+1][j+1][k+1]+=dp[i][j][k]*(n-j)*(m-k)/(double)(m*n-i); if(j<n||k<m) dp[i+1][j][k]+=dp[i][j][k]*(j*k-i)/(double)(m*n-i); } double s=0; for(int i=1; i<=n*m; i++) s+=dp[i][n][m]*i; printf("%.12f\n",s); } return 0; }