您的位置:首页 > 其它

ZOJ 3822 Domination The 2014 ACM-ICPC 牡丹江区域赛 概率dp 先算概率,再转成期望

2014-10-12 20:57 387 查看
DominationTime 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 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 <= 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
以前做的期望题都是直接从后往前推,但是这题是要先从前往后算出概率,然后再计算期望。给跪了,思路是别人的。。。
dp数组里没维代表【当前步数】【当前覆盖行数】【当前覆盖列数】
然后注意下当全覆盖后,就不能再转移了。所以dp【i】【n】【m】 是不能再转移给 dp【i+1】【n】【m】的.因当全覆盖的时候已经结束了。
其他的转移都有备注
#include<stdio.h>#include<string.h>double dp[3000][55][55];int main(){	double ans;	int t,n,m,tem;	scanf("%d",&t);	while(t--)	{		scanf("%d%d",&n,&m);		memset(dp,0,sizeof(dp));		dp[0][0][0]=1.0;		ans=0;		for(int i=1;i<=n*m;i++)//步数		{			//printf("第%d步\n",i);			for(int j=1;j<=n;j++)//覆盖了几行			{				for(int k=1;k<=m;k++)//覆盖了几列				{					tem=n*m-i+1; //总数					if(j==n&&k==m)//这就不能再从本来的全覆盖转移过来了,						dp[i][j][k]= dp[i-1][j-1][k-1]*((double)(n-(j-1))*(m-(k-1))/tem)//下的那块 行列都没被覆盖过						+dp[i-1][j-1][k]*((double)(n-(j-1))*k/tem)//行没被覆盖 列已经被覆盖					    +dp[i-1][j][k-1]*((double)j*(m-(k-1))/tem);//行已经被覆盖 列还没被覆盖					else 						dp[i][j][k]= dp[i-1][j-1][k-1]*((double)(n-(j-1))*(m-(k-1))/tem)//下的那块 行列都没被覆盖过						+dp[i-1][j-1][k]*((double)(n-(j-1))*k/tem)//行没被覆盖 列已经被覆盖					    +dp[i-1][j][k-1]*((double)j*(m-(k-1))/tem)//行已经被覆盖 列还没被覆盖						+dp[i-1][j][k]*((double)(j*k-(i-1))/tem);//被覆盖过的那些点中  还未被覆盖的点  					//上面这行 较上面要减去(i-1)是因为这里将要下的地方是行列都被覆盖过的,所以其中的点有(i-1)个已经被覆盖过,要减去					//printf("%.1lf ",dp[i][j][k]);				}				//puts("\n");			}		}		for(int i=1;i<=n*m;i++)		{			ans+=dp[i][m]*i;//i天后 全覆盖的概率 乘上i 就是期望		}		printf("%.12lf\n",ans);	}	return 0;}/*30 100 70100 130 30-100 -70 40*/  

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐