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。
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; } }
相关文章推荐
- UVA - 1639 Candy (概率,精度)
- UVa1639 - Candy(期望+对数精度处理)
- uva 1639 Candy | ACM\ICPC Chengdu 2012 (期望)
- UVA 1639(p333)----Candy
- UVA.1639 Candy (期望 高精度)
- UVa 1639 Candy (数学期望+组合数学+高精度存储)
- UVa 1639 (期望) Candy
- [UVA1639] Candy && 数学期望
- UVa 1639 Candy
- UVA 1639——Candy(期望,精度处理)
- UVA 1639 Candy (组合数+精度)
- 【数学期望】Candy, ACM/ICPC Chengdu 2012, UVa1639 【精度】
- UVa 1639 Candy
- uva 1639 Candy (对数处理精度)
- uva 1639 Candy 大数的对数处理 数学期望
- uva1639 Candy 数学期望 对数处理精度
- UVA - 1639 Candy——期望+log处理精度
- UVa1639糖果(紫书333)(期望)
- UVA 1639
- 例题10-17 糖果 UVa1639