题目链接
Domination Time Limit: 8 Seconds Memory Limit: 131072 KB Special JudgeEdward 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.
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).
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.
2 1 3 2 2
3.000000000000 2.666666666667Author: JIANG, Kai
题意:n*m的棋盘,每天任意放一个棋子,当每行与每列都有棋子的时候,停止放旗子,问放棋子数的期望。一个格子只能放一个棋子。
题解:对于求期望或求概率的题目。如果用dp来求,一般都是用dp[ s ] 来表示从s状态变到目标状态的期望或概率。
这题我们用dp[ i ][ j ][ k ] 表示现在有 i 行有棋子,有 j 列有棋子,并且放了k个棋子,从当前状态变到目标状态的期望次数。
那么答案就是dp[ 0 ][ 0 ][ 0 ] 。
转移就是:dp[ i ][ j ][ k ]=0:
1,若棋盘没有放满即 i<n || j<m,且i*j>k ,把棋子放在行列均有棋子的地方 : dp[ i ][ j ][ k ]+=(dp[ i ][ j ][ k+1 ]+1)*( i*j-k )/( n*m-k )。
2,若i<n&&j>0 , 可以把棋子放在新的一行,但是列已经有棋子: dp[ i ][ j ][ k ]+=(dp[ i+1 ][ j ][ k+1 ]+1)*(n-i)*j/(n*m-k)。
3,若j<m&&i>0,可以把棋子放在新的一列,且行已经有棋子:dp[ i ][ j ][ k ]+=(dp[ i ][ j+1 ][ k+1 ]+1 )*(m-j)*i/(n*m-k)。
4,若i<n&&j<m,可以放一个棋子在新的一行,也在新的一列: dp[ i ][ j ][ k ]+=(dp[ i+1 ][ j+1 ][ k+1 ]+1)*(n-i)*(m-j)/(n*m-k)。
我是用记忆化搜索的形式实现的,复杂度O(n^4)。
代码如下:
#include<iostream> #include<algorithm> #include<string.h> #include<stdio.h> #include<string> #include<math.h> using namespace std; double dp[55][55][55*55]; bool use[55][55][55*55]; int n,m; double dfs(int x,int y,int nu) { if(use[x][y][nu]) return dp[x][y][nu]; use[x][y][nu]=true; dp[x][y][nu]=0; if(x<n&&y>0) { dp[x][y][nu]+=(dfs(x+1,y,nu+1)+1.0)*(n-x)*1.0*y/(1.0*(n*m-nu)); } if(y<m&&x>0) { dp[x][y][nu]+=(dfs(x,y+1,nu+1)+1.0)*(m-y)*1.0*x/(1.0*(n*m-nu)); } if((x<n||y<m)&&x*y>nu) { dp[x][y][nu]+=(dfs(x,y,nu+1)+1.0)*(x*y-nu)*1.0/(1.0*(n*m-nu)); } if(x<n&&y<m) { dp[x][y][nu]+=(dfs(x+1,y+1,nu+1)+1.0)*(n-x)*1.0*(m-y)/(1.0*(n*m-nu)); } return dp[x][y][nu]; } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); memset(use,false,sizeof(use)); printf("%.10lf\n",dfs(0,0,0)); } return 0; }