ZOJ Problem Set - 3822

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 withN 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 ofN × 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 <= 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

max(n,m)<天数<n*m

令数组dp[i][j][k]表示第k天的时候有i行j列棋盘已经摆放了棋子

dp[i][j][k]+=dp[i-1][j][k-1]*(n-i+1)/(s-k+1)

dp[i][j][k]+=dp[i][j-1][k-1]*(m-j+1)/(s-k+1)

dp[i][j][k]+=dp[i-1][j-1][k-1]*(m-j+1)*(n-i+1)/(s-k+1)

dp[i][j][k]+=dp[i][j][k-1]*(i*j-k)/(s-k+1)

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int MAXN=55;
double dp[MAXN][MAXN][MAXN*MAXN];
int main()
{
    int t,n,m;
    double ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        ans=0;
        memset(dp,0,sizeof(dp));
        dp[1][1][1]=1;
        for(int i=1;i<=n;i++)///dp[i][j][k],有i行和j列摆放有棋子,棋子数为k颗
        {
            for(int j=1;j<=m;j++)
            {
                for(int k=max(i,j);k<=i*j;k++)
                {
                    if(i==n&&j==m)
                        break;
                    dp[i+1][j][k+1]+=dp[i][j][k]*(double)(n-i)*j/(double)(n*m-k);
                    dp[i][j+1][k+1]+=dp[i][j][k]*(double)(m-j)*i/(double)(n*m-k);
                    dp[i+1][j+1][k+1]+=dp[i][j][k]*(double)(n-i)*(m-j)/(double)(n*m-k);
                    dp[i][j][k+1]+=dp[i][j][k]*(double)(i*j-k)/(double)(n*m-k);
                }
            }
        }
        for(int k=max(n,m);k<=n*m;k++)
        {
            ans+=dp[n][m][k]*k;
            //cout<<dp[n][m][k]*k<<endl;
            //cout<<" "<<ans<<endl;
        }
        printf("%.12f\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38144740/article/details/79174300