ZOJ 3822 Domination The 2014 ACM-ICPC 牡丹江区域赛 概率dp 先算概率,再转成期望

来源:互联网 发布:线切割制图软件 编辑:程序博客网 时间:2024/05/01 22:00
Domination

Time Limit: 8 Seconds      Memory Limit: 131072 KB      Special Judge

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 <= NM <= 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

21 32 2

Sample Output

3.0000000000002.666666666667
以前做的期望题都是直接从后往前推,但是这题是要先从前往后算出概率,然后再计算期望。给跪了,思路是别人的。。。
dp数组里没维代表【当前步数】【当前覆盖行数】【当前覆盖列数】
然后注意下当全覆盖后,就不能再转移了。所以dp【i】【n】【m】 是不能再转移给 dp【i+1】【n】【m】的.因当全覆盖的时候已经结束了。
其他的转移都有备注
#include<stdio.h>#include<string.h>double dp[3000][55][55];int main(){double ans;int t,n,m,tem;scanf("%d",&t);while(t--){scanf("%d%d",&n,&m);memset(dp,0,sizeof(dp));dp[0][0][0]=1.0;ans=0;for(int i=1;i<=n*m;i++)//步数{//printf("第%d步\n",i);for(int j=1;j<=n;j++)//覆盖了几行{for(int k=1;k<=m;k++)//覆盖了几列{tem=n*m-i+1; //总数if(j==n&&k==m)//这就不能再从本来的全覆盖转移过来了,dp[i][j][k]= dp[i-1][j-1][k-1]*((double)(n-(j-1))*(m-(k-1))/tem)//下的那块 行列都没被覆盖过+dp[i-1][j-1][k]*((double)(n-(j-1))*k/tem)//行没被覆盖 列已经被覆盖    +dp[i-1][j][k-1]*((double)j*(m-(k-1))/tem);//行已经被覆盖 列还没被覆盖else dp[i][j][k]= dp[i-1][j-1][k-1]*((double)(n-(j-1))*(m-(k-1))/tem)//下的那块 行列都没被覆盖过+dp[i-1][j-1][k]*((double)(n-(j-1))*k/tem)//行没被覆盖 列已经被覆盖    +dp[i-1][j][k-1]*((double)j*(m-(k-1))/tem)//行已经被覆盖 列还没被覆盖+dp[i-1][j][k]*((double)(j*k-(i-1))/tem);//被覆盖过的那些点中  还未被覆盖的点  //上面这行 较上面要减去(i-1)是因为这里将要下的地方是行列都被覆盖过的,所以其中的点有(i-1)个已经被覆盖过,要减去//printf("%.1lf ",dp[i][j][k]);}//puts("\n");}}for(int i=1;i<=n*m;i++){ans+=dp[i][n][m]*i;//i天后 全覆盖的概率 乘上i 就是期望}printf("%.12lf\n",ans);}return 0;}/*30 100 70100 130 30-100 -70 40*/  


                                             
0 0