uva1639 Candy

229 篇文章 0 订阅
137 篇文章 0 订阅

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[n]-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[n]-lnfac[n-i])
              +exp((n+1)*log(1.0-p)+(n-i)*log(p)+lnfac[2*n-i]-lnfac[n]-lnfac[n-i]));
        cout.setf(ios::fixed);
        cout<<"Case "<<++K<<": "<<fixed<<setprecision(6)<<ans<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值