期望公式很好推,要注意空的盒子总共被取了N+1次,而不是N次。
但是在N很大的时候公式中的组合数会巨大,而且p的N次方也会非常小。这样就要像一个方法压缩他们,就是对这些数取log,然后再用exp函数还原(e的n次方)
对于组合数,先预处理出1到2e5这些数阶乘的log,再用这些阶乘去算组合数。
对于p的n次方,它的log等于n*log(p)
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#include <cmath>
#define maxn 400005
double F[maxn];
double C[maxn];
int N;
double p;
void init(){
for(int i=2;i<=maxn;i++){
F[i]=F[i-1]+log(i);
}
}
double Pow(double p,int n){
double res=1;
while(n--) res*=p;
return res;
}
int main(){
init();
int kase=1;
while(~scanf("%d%lf",&N,&p)){
for(int i=0;i<N;i++){
C[i]=F[i+N]-F[i]-F[N];
}
double res=0;
double k1=log(p),k2=log(1-p);
for(int i=0;i<N;i++){
double tmp;
tmp=(N+1)*k1+i*k2+C[i];
res+=(N-i)*exp(tmp);
tmp=(N+1)*k2+i*k1+C[i];
res+=(N-i)*exp(tmp);
}
printf("Case %d: %.6f\n",kase++,res);
}
return 0;
}