hdu 4465 Candy (非原创)

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 first box with probability p and the second box with probability (1 - p). For the chosen box, if there are still candies in it, he eats one of them; otherwise, he will be sad and then open the other box. 
He has been eating one candy a day for several days. But one day, when opening a box, he finds no candy left. Before opening the other box, he wants to know the expected number of candies left in the other box. Can you help him?

InputThere are several test cases. 
For each test case, there is a single line containing an integer n (1 ≤ n ≤ 2 × 10 5) and a real number p (0 ≤ p ≤ 1, with 6 digits after the decimal). 
Input is terminated by EOF.OutputFor each test case, output one line “Case X: Y” where X is the test case number (starting from 1) and Y is a real number indicating the desired answer. 
Any answer with an absolute error less than or equal to 10 -4 would be accepted.Sample Input

10 0.400000
100 0.500000
124 0.432650
325 0.325100
532 0.487520
2276 0.720000

Sample Output

Case 1: 3.528175
Case 2: 10.326044
Case 3: 28.861945
Case 4: 167.965476
Case 5: 32.601816
Case 6: 1390.500000

参考博客:https://www.cnblogs.com/xcw0754/p/4753221.html

题意:有两个盒子各有n个糖(n<=2*105),每天随机选1个(概率分别为p,1-p),然后吃掉一颗糖。直到有一天打开盒子一看,这个盒子没有糖了。输入n,p,求此时另一个盒子里糖的个数的数学期望。

思路:假设没糖的是A盒子,而B盒子还有0~n个糖。由于B盒子还有0个糖的情况的期望必为0,所以省略,只需要计算1~n的。

  (1)当A盒没有糖时,B盒就可能有1~n个糖,概率为C(n+i,i)*(pn+1)*(1-p)n-i。为啥还带个大C?这是情况的种数(想象取糖时还有个顺序,有C种可能的顺序),不然的话,单靠这两个小于1的数是超级小的。

  (2)根据(1)种的概率公式,穷举B盒可能还有 i 个糖,那么对于每种情况,期望值为i*C(n+i,i)*(pn+1)*(1-p)n-i,累加这些期望值就行了。同理,B盒没有糖也是这样算,只是概率换成了(1-p)。两种情况的累加期望就是答案。

  (3)这样还是不行,求C时会爆LL,对p求幂时结果又太小,精度损失严重。C(n+i,i)*(pn+1)*(1-p)n-i这个式子的结果本身是不大的。考虑取这个式子对数,化成相加的形式x=logC(n+i,i)+ log(pn+1)+log(1-p)n-i ,(注意指数可以提到前面作为乘的形式),求出x作为指数来求ex这样就OK了(这个函数是exp(x) )。

  (4)这个C还是很难求,比如当n=200000时,i 还没有到10时,C(200000+10, 10)就爆了。对此,由于在穷举i时,C(n+i,i)是可以递推的,那么我们可以先将C给逐步取对数,再相加就行了。递推是这样的,c+=log((n+i)/i)。

  (5)总复杂度是O(n)。时间在500ms以下。

ac代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <string>
 5 #include <iostream>
 6 #include <cmath>
 7 #include <iomanip>
 8 using namespace std;
 9 typedef long long ll;
10 int n;double p;
11 double solve(int n,double p)
12 {
13     double c=0;
14     double ans=n*exp((n+1)*log(p));
15   //  cout<<ans<<endl;
16     for(int i=1;i<n;++i)
17     {
18         c+=log((n+i)*1.0/(i*1.0));
19         ans+=(n-i)*exp(c+(n+1)*log(p)+i*log(1-p));
20    //     cout<<ans<<endl;
21     }
22     return ans;
23 }
24 int main()
25 {
26     cout<<setiosflags(ios::fixed)<<setprecision(6);
27     int cas=1;
28     while(cin>>n>>p)
29     {
30         
31         double res=solve(n,p)+solve(n,1-p);
32         cout<<"Case "<<cas++<<": "<<res<<endl;
33     }
34 }
View Code
原文地址:https://www.cnblogs.com/zmin/p/8370846.html