题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4586
Problem Description
There is a dice with n sides, which are numbered from 1,2,...,n and have the equal possibility to show up when one rolls a dice. Each side has an integer ai on it. Now here is a game that you can roll this dice once, if the i-th side is up, you will get ai
yuan. What‘s more, some sids of this dice are colored with a special different color. If you turn this side up, you will get once more chance to roll the dice. When you roll the dice for the second time, you still have the opportunity to win money and rolling
chance. Now you need to calculate the expectations of money that we get after playing the game once.
Input
Input consists of multiple cases. Each case includes two lines.
The first line is an integer n (2<=n<=200), following with n integers ai(0<=ai<200)
The second line is an integer m (0<=m<=n), following with m integers bi(1<=bi<=n), which are the numbers of the special sides to get another more chance.
Output
Just a real number which is the expectations of the money one can get, rounded to exact two digits. If you can get unlimited money, print inf.
Sample Input
6 1 2 3 4 5 6 0 4 0 0 0 0 1 3
Sample Output
3.50 0.00
Source
转载:
题意:一个骰子有 n 面,每一面有不同的数字a[i],再给一个m,给m个面,这些面如果被骰到,可以继续多骰一次,问你骰一次得到数字的期望是多少?
解题思路:开始我在推公式,但是由于思维方式不对,算的 有点麻烦,其实转化一个思路就可以了。我们要算骰骰子得出的概率,我开始想的就是sum1是(n-m)非特殊面的和,sum2是特殊面的和,那么骰一次的概率就是
sum1*[(n-m)/n],骰两次的概率是(sum2*(m/n)+sum1*(m/n)*[(n-m)/n],第三次是sum2*(m/n)*(m/n)+sum1*(m/n)*(m/n)*[(n-m)/n] 如此这样递推可以将最终的解求出。最终可以得到的解是(sum1+sum2)+(sum1+sum2)*(m/n)+(sum1+sum2)*(m/n)^2+....+... 记sum1+sum2=sum这样是无穷等比数列,可以使用公式得到p=sum*[(n)/(n-m)],然后这是总期望,还需要除以面数n,得到答案为sum/(n-m).
其实也可以换一条思路,由于是无限,我们可以看作是
只考虑第一次,获得的金币的平均值为sum/n.sum为所有色子的面的金币值相加。
对于运气好,摇中了可以再来一次,该轮就能获得m/n*(sum/n)
运气好,又再来一次,该轮能获得(m/n)^2*(sum/n)
无穷无尽的摇下去,一共能获得sum/n*(1+q + q^2+`````+q^k + ````)其实就是个等比数列,其中公比为q = m/n
将式子化简,就能得到E = sum/(n-m) 或者 E = a1/(1-q),其中a1 = sum/n。所以当sum = 0时为0,n = m时为inf。其余就为sum/(n-m)。
不过这个题目需要特判,如果sum = 0首先输出0.00,然后是n == m,输出inf。因为题目会卡你sum==0且n==m这组答案。
代码如下:
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <iostream> using namespace std; int main() { int n, m; int a[247], b[247]; while(~scanf("%d",&n)) { int sum = 0; for(int i = 0; i < n; i++) { scanf("%d",&a[i]); sum+=a[i]; } scanf("%d",&m); for(int i = 0; i < m; i++) { scanf("%d",&b[i]); } double a1, q; a1 = sum*1.0/n; q = m*1.0/n; if(a1 == 0) { printf("0.00\n"); } else if(q == 1) { printf("inf\n"); } else { printf("%.2lf\n",a1/(1-q)); } } return 0; }