首页 > 代码库 > zoj 3822 Domination (概率DP)

zoj 3822 Domination (概率DP)

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 Mcolumns.

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

2
1 3
2 2

Sample Output

3.000000000000
2.666666666667

题意:向一个N*M的棋盘里随机放棋子,每天往一个格子里放一个。求每一行每一列都有棋子覆盖的天数。

思路:开一个三维数组,dp[i][j][k]:有i行j列被k个棋子覆盖的概率。

则dp[i+1][j][k+1]=dp[i][j][k]*(n-i)*j/(n*m-k);      //增加一个棋子,多覆盖一行

dp[i][j+1][k+1]=dp[i][j][k]*i*(m-j)/(n*m-k);        //增加一个棋子,多覆盖一列

dp[i+1][j+1][k+1]=dp[i][j][k]*(n-i)*(m-j)/(n*m-k);  //增加一个棋子,多覆盖一行及一列

dp[i][j][k+1]=dp[i][j][k]*(i*j-k)/(n*m-k);    //增加一个棋子,行、列数没有增加

则ans=dp[n][m][k]*k,(k=0...n*m). //当i==n&&j==m时特殊处理,最后一项去掉。

易知dp[0][0][0]=1;

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define N 55
#define LL __int64
const int inf=0x1f1f1f1f;
const double eps=1e-10;
double dp[N][N][N*N];
int n,m;
void inti()
{
    int i,j,k;
    for(i=0;i<=n;i++)
    {
        for(j=0;j<=m;j++)
        {
            for(k=0;k<=n*m;k++)
                dp[i][j][k]=0;
        }
    }
}
int main()
{
    int i,j,k,T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        inti();
        dp[0][0][0]=1;
        int tt=n*m;
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                for(k=0;k<=n*m;k++)
                {
                    if(i==n&&j==m)
                        dp[i][j][k]=(dp[i-1][j][k-1]*(n-i+1)*j+dp[i][j-1][k-1]*i*(m-j+1)+dp[i-1][j-1][k-1]*(n-i+1)*(m-j+1))/(tt-k+1);
                    else
                        dp[i][j][k]=(dp[i-1][j][k-1]*(n-i+1)*j+dp[i][j-1][k-1]*i*(m-j+1)+dp[i-1][j-1][k-1]*(n-i+1)*(m-j+1)+dp[i][j][k-1]*(i*j-k+1))/(tt-k+1);
                }
            }
        }
        double ans=0;
        for(i=0;i<=tt;i++)
            ans+=dp[n][m][i]*i;
        printf("%.9f\n",ans);
    }
    return 0;
}



zoj 3822 Domination (概率DP)