您的位置:首页 > 其它

uva1639 Candy

2016-09-12 18:33 399 查看
LazyChild is a lazy child who likes candy very much. Despite being

very young, he has two large candy boxes, each contains n candies

initially. Everyday he chooses one box and open it. He chooses the

rst box with probability p and the second box with probability (1

不妨设最后一个打开的是第一个盒子【最后打开的是第二个同理】,第二个盒子还剩i个,那么对应的数学期望为C(2 * n-i,n) * p^(n+1)【最后又打开一次】 * (1-p)^(n-i)*i。

这个式子是对的,但是有两个问题,一个是C太大,存不下,二是p^n太小,有精度误差。

所以可以利用对数,计算i*e^((n+1) * ln(p)+(n-i) * ln(1-p)+lnfac[2 * n-i]-lnfac
-lnfac[n-i]),其中lnfac[x]表示ln(x!),可以预处理出来。这样计算过程中就不会出现太大或者太小的数了。

还要注意,这样对精度要求还是不够的,需要用到long double。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<iomanip>
using namespace std;
#define LD long double
const LD eps=1e-14;
LD lnfac[400010];
int main()
{
int i,j,k,m,n,K=0;
LD x,y,z,p,q,ans;
for (i=2;i<=400000;i++)
lnfac[i]=lnfac[i-1]+log(i);
while (cin>>n>>p)
{
if (p<=eps||fabs(1-p)<=eps)
{
printf("Case %d: %d.000000\n",++K,n);
continue;
}
ans=0;
for (i=1;i<=n;i++)
ans+=i*(exp((n+1)*log(p)+(n-i)*log(1.0-p)+lnfac[2*n-i]-lnfac
-lnfac[n-i])
+exp((n+1)*log(1.0-p)+(n-i)*log(p)+lnfac[2*n-i]-lnfac
-lnfac[n-i]));
cout.setf(ios::fixed);
cout<<"Case "<<++K<<": "<<fixed<<setprecision(6)<<ans<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数学期望 精度