admin管理员组

文章数量:1582954

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 Tindicating 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[k][i][j] 表示 放了k个 已经有i行 j列 满足条件然后就可以分4种情况了  在放一个 加一行,加一列,都不变,都加1 详见代码

#include<iostream>
#include<cstdio>
#include<cstring> 
using namespace std;
const int N=51;
int n,m;
double dp[N*N][N][N];
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		scanf("%d%d",&n,&m);
		memset(dp,0,sizeof(dp));
		dp[0][0][0]=1;
		for(int k=0;k<=n*m;k++)
			for(int i=0;i<=n;i++)
				for(int j=0;j<=m;j++)
				{
					if(i==n&&j==m) continue;//当然 已经满足条件后就不要继续求了 
					if(i*j>=k) dp[k+1][i][j]+=dp[k][i][j]*(i*j-k)/(n*m-k);
					if(i<n) dp[k+1][i+1][j]+=dp[k][i][j]*(n-i)*j/(n*m-k);
					if(j<m) dp[k+1][i][j+1]+=dp[k][i][j]*(m-j)*i/(n*m-k);
					if(i<n&&j<m) dp[k+1][i+1][j+1]+=dp[k][i][j]*(n-i)*(m-j)/(n*m-k);
				}
		double ans=0;
		for(int i=max(n,m);i<=n*m;i++)ans+=dp[i][n][m]*i;
		printf("%.12f\n",ans);
	}	
	return 0;
}

 

本文标签: 概率ZOJDP