首页 > 代码库 > 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 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 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个棋子覆盖的概率(不管

棋子放到哪,都可以移到左上角的相应地方,k就是区域1中叉的个数)。

技术分享

当棋子放到区域1时: dp[i][j][k]=(r*c-k)/(n*m-k)*dp[i][j][k+1];

当棋子放到区域2时: dp[i][j][k]=(n-r)*c/(n*m-k)*dp[i+1][j][k+1];

当棋子放到区域3时: dp[i][j][k]=r*(m-c)/(n*m-k)*dp[i][j+1][k+1];

当棋子放到区域4时: dp[i][j][k]=(n-r)*(m-c)/(n*m-k)*dp[i+1][j+1][k+1];

最后注意下放到每个区域对应的条件就OK了。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=55;

double dp[maxn][maxn][maxn*maxn];
bool visited[maxn][maxn][maxn*maxn];
int n,m;

double DP(int r,int c,int num)
{
    if(visited[r][c][num])  return dp[r][c][num];
    if(r==0 || c==0)   return DP(r+1,c+1,num+1)+1;
    if(r>=n && c>=m)   return 0;
    double ans=0.0,p=n*m-num,q=r*c-num;
    if(num<r*c)        ans+=q/p*DP(r,c,num+1);
    if(r<n)            ans+=(n-r)*c/p*DP(r+1,c,num+1);
    if(c<m)            ans+=r*(m-c)/p*DP(r,c+1,num+1);
    if(r<n && c<m)     ans+=(n-r)*(m-c)/p*DP(r+1,c+1,num+1);
    visited[r][c][num]=1;
    return dp[r][c][num]=ans+1;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&n,&m);
        memset(visited,0,sizeof(visited));
        printf("%.12f\n",DP(0,0,0));
    }
    return 0;
}


ZOJ 3822 Domination (概率DP)