解题报告 之 ZOJ 3822 Domination

来源:互联网 发布:nginx 快速配置 编辑:程序博客网 时间:2024/06/10 03:37

解题报告 之 ZOJ 3822 Domination


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

题目大意:一个n*m的矩形,每次放置一个棋子在某个空位置上,且是等概率的。问要使得整个棋盘的每一行和每一列都至少有一个棋子,所需要的步骤的期望是多少?

分析:一道典型的概率DP。概率DP的基础模型可以看下kuangbin大神的总结: 概率DP大题的思路就是从终态一直向之前的状态转移。(http://www.cnblogs.com/kuangbin/archive/2012/10/02/2710606.html)
这道题一开始可能会被认为是kuangbin帖子中的模型二,但是仔细思考之后发现,有一个重要的区别在于这道题放置过棋子的地方就不能再放了,所以对于dp(i, j)来说,根据已经使用的棋子不同,转移到之后的状态并不是等概率的,所以要讨论已经使用的棋子的个数,那么就从二维变成三维。

具体来说,用dp[i][j][k]表示现在使用了k个棋子使得有i行,有j列上有棋子了,为了达到终态还需要的步骤。
对于所有可能的k,可以转移的状态有 dp[i][j][k+1], dp[i+1][j][k+1], dp[i][j+1][k+1], dp[i+1][j+1][k+1]。分别对应四种情况。
最后的答案就是dp[0][0][0],即从初态到终态所需要的次数。算概率的时候注意要减掉已经有棋子的格子。

上代码:
 
#include <iostream>#include <cmath>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 50 + 10;double dp[MAXN][MAXN][MAXN*MAXN];int main(){int T;scanf( "%d", &T );while(T--){memset( dp, 0, sizeof dp );int n, m;scanf( "%d%d", &n, &m );for(int i = n; i >= 0; i--){for(int j = m; j >= 0; j--){if(i == n&&j == m) continue; //因为没有状态会转移到这个状态,否则会出现除零错误for(int k = i*j; k >= max( i, j ); k--) //注意细节,k可能的范围就是 i*j 到 max(i,j)。{//如果使用了超过i*j个棋子则不可能只有i行、j列有棋子。//如果连max(i,j)个棋子都没有,则不可能占i行或j列//注意先算概率,再乘dp,不然可能会爆。算概率的时候注意已经放过的地方要去除,所以-kdp[i][j][k] += (double)j*(n - i) / (n*m - k)*dp[i + 1][j][k + 1];dp[i][j][k] += (double)i*(m - j) / (n*m - k)*dp[i][j + 1][k + 1];dp[i][j][k] += (double)(i*j - k) / (n*m - k)*dp[i][j][k + 1]; //这里分子-k的原因是只能从这i*j的矩形中去选,所以要去除已经有棋子的格子dp[i][j][k] += (double)(n - i)*(m - j) / (n*m - k)*dp[i + 1][j + 1][k + 1];dp[i][j][k] += 1.0;//别忘了步骤加1}}}printf( "%.12lf\n", dp[0][0][0] ); //输出初态到终态所需要的步骤}return 0;}

0 0
原创粉丝点击