ZOJ 3551 Bloodsucker
In 0th day, there are n-1 people and 1 bloodsucker. Every day, two and only two of them meet. Nothing will happen if they are of the same species, that is, a people meets a people or a bloodsucker meets a bloodsucker. Otherwise, people may be transformed into bloodsucker with probability p. Sooner or later(D days), all people will be turned into bloodsucker. Calculate the mathematical expectation of D.
Input
The number of test cases (T, T ≤ 100) is given in the first line of the input. Each case consists of an integer n and a float number p (1 ≤ n < 100000, 0 < p ≤ 1, accurate to 3 digits after decimal point), separated by spaces.
Output
For each case, you should output the expectation(3 digits after the decimal point) in a single line.
Sample Input
1 2 1
Sample Output
1.000
概率DP入门题
设dp[i]表示从i个吸血鬼变成n个吸血鬼的期望天数,p1是已有i个吸血鬼时第二天有人变成吸血鬼的概率,p2是没人变成吸血鬼的概率。
则:dp[i]=(dp[i+1]+1)*p1+(dp[i]+1)*p2
移项后化简得: p1*dp[i]=dp[i+1]*p1+1
注意这里是倒着做的,因为dp[n]=0,所以可以逆着求出dp[n-1]…dp[1]
1 #include<iostream> 2 #include<cstdio> 3 4 using namespace std; 5 6 long n; 7 double p,p1; 8 double dp[100001]; 9 10 int main() 11 { 12 int t; 13 14 cin>>t; 15 16 while(t--) 17 { 18 cin>>n>>p; 19 20 dp[n]=0; 21 22 for(int i=n-1;i>=1;i--) 23 { 24 double down=n; 25 down*=(n-1); 26 down/=2; 27 double up=i; 28 up*=(n-i); 29 p1=up/down*p; 30 dp[i]=dp[i+1]+1.0/p1; 31 } 32 33 printf("%.3lf\n",dp[1]); 34 } 35 36 return 0; 37 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步