首页 > 学院 > 开发设计 > 正文

彩球 概率期望

2019-11-08 00:42:08
字体:
来源:转载
供稿:网友

题目描述

  袋子里有n个球。每次依次取出两个,把第二个球涂成第一个球的颜色,然后放回袋里搅匀。你的任务是算出在平均情况下,让所有球的颜色相同所需要的取多少次球(即:次数的数学期望)。

题目大意

  略A.A

数据范围

  字符串长度小于25

样例输入

ball.in AB ball.in ZCZ ball.in KLM ball.in AAABB

样例输出

ball.out 1.000000 ball.out 3.000000 ball.out 4.000000 ball.out 11.666667

解题思路

设f[i][j][k]为操作k次,第i种颜色有j个的概率 f[i][j+1][p+1]+=f[i][j][p]×(j/len)×((len-j)/(len-1)); f[i][j-1][p+1]+=f[i][j][p]×(len-j/len)×(j/(len-1)); f[i][j][p+1]+=f[i][j][p]×(j/len)×((j-1)/(len-1)); f[i][j][p+1]+=f[i][j][p]×((len-j)/len)×((len-j-1)/(len-1)); 答案=∑∞step=0f[i][len][step]

代码

#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;inline int Getint(){int x=0,f=1;char ch=getchar();while('0'>ch||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}int main(){ int g[35],len; double f[2][35][35],Ans=0; memset(f,0,sizeof(f)); memset(g,0,sizeof(g)); string str; cin>>str; len=str.length(); for(int i=0;i<len;i++)g[str[i]-'A'+1]++; for(int i=1;i<=26;i++)if(g[i]){f[0][i][g[i]]=1.0;} bool p=0; for(int step=1;step<=10000;step++){ p^=1; memset(f[p],0,sizeof(f[p])); for(int i=1;i<=26;i++){ for(int j=1;j<len;j++){//浮点数运算太多,程序太慢 f[p][i][j+1]+=f[p^1][i][j]*(double(j)/len)*(double((len-j))/(len-1)); f[p][i][j-1]+=f[p^1][i][j]*(double((len-j))/len)*(double(j)/(len-1)); f[p][i][j]+=f[p^1][i][j]*(double(j)/len)*(double((j-1))/(len-1)); f[p][i][j]+=f[p^1][i][j]*(double((len-j))/len)*(double((len-j-1))/(len-1)); } } for(int i=1;i<=26;i++)Ans+=step*f[p][i][len]; } PRintf("%.6lf",Ans); return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表