ZOJ - 3822 概率dp

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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值