HDU 4465 Candy

Candy

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2520    Accepted Submission(s): 1100
Special Judge

 

Problem Description
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?

Input
There are several test cases.
For each test case, there is a single line containing an integer $n (1 \leq n \leq 2 \times 10^5) $and a real number p ($0\leq p \leq 1$, with 6 digits after the decimal).
Input is terminated by EOF.

Output
For 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
 

 

Source

 解题:公式题

 首先可以算出公式

\[\sum_{i = 0}^{n-1}\binom{n}{n+i}\times (p^{n+1}\times (1-p)^i + (1-p)^{n+1}\times p^i)\times (n-i)\]

我们至少要拿n个,才会出现一个盒子里面的糖果空,所以假设第一个为空,枚举第二个盒子剩余的糖果数量,或者假设第二个盒子为空,枚举第一个盒子剩余的糖果数量。

但是,更加狗血的事情发生了,会导致double溢出,你说用long double啊?呵呵,naive!还是要溢出,日了整个世界,好吧,使用log吧。换成对数,把*变成+

 算$\binom{n}{n+i}$ 是可以滚动着算的

可以发现在取对数后有:

$$C_{0} = 0,C_i = C_{i-1} + log(n + i) - log(i)$$

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     int n,cs = 1;
 5     double p;
 6     while(~scanf("%d%lf",&n,&p)) {
 7         double ret = 0,tmp,c = 0,logp = log(p),log_p = log(1 - p);
 8         for(int i = 0; i < n; ++i) {
 9             double logn_i = log(n-i);
10             tmp = c + (n + 1)* logp + i*log_p + logn_i;
11             ret += exp(tmp);
12             tmp = c + (n + 1)*log_p + i*logp + logn_i;
13             ret += exp(tmp);
14             c += log(n + i + 1.0) - log(i + 1.0);
15         }
16         printf("Case %d: %.6f\n",cs++,ret);
17     }
18     return 0;
19 }
View Code

 

转载于:https://www.cnblogs.com/crackpotisback/p/4776556.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值