A Dangerous Maze (n次伯努利试验中,期望和概率)

You are in a maze; seeing n doors in front of you in beginning. You can choose any door you like. The probability for choosing a door is equal for all doors.

If you choose the ith door, it can either take you back to the same position where you begun in xi minutes, or can take you out of the maze after xi minutes. If you come back to the same position, you can't remember anything. So, every time you come to the beginning position, you have no past experience.

Now you want to find the expected time to get out of the maze.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case contains a blank line and an integer n (1 ≤ n ≤ 100) denoting the number of doors. The next line contains nspace separated integers. If the ith integer (xi) is positive, you can assume that the ith door will take you out of maze after xi minutes. If it's negative, then the ith door will take you back to the beginning position after abs(xi) minutes. You can safely assume that 1 ≤ abs(xi) ≤ 10000.

Output

For each case, print the case number and the expected time to get out of the maze. If it's impossible to get out of the maze, print 'inf'. Print the result in p/q format. Where p is the numerator of the result and q is the denominator of the result and they are relatively prime. See the samples for details.

Sample Input

3

 

1

1

 

2

-10 -3

 

3

3 -6 -9


题意:有n扇门,下一行有n个数,负数,如-6代表着,过6分钟,你就和回到原来的位置,正数,如6,代表着过6分钟,你就出去这个迷宫了;当你回到原点时,你原来的记忆将被清除;问你出迷宫所花费时间的期望。输出结果写出分数形式,且分子分母互质,若不能出迷宫输出inf。

A Dangerous Maze (n次伯努利试验中,期望和概率)_第1张图片

思路:因为当t为负数时,清除记忆,所以可以是无数次独立实验,满足伯努利试验,假设n扇门中,有k个正数,那么平均选n次,有k次一次能出去,所以出去的概率 k/n, 所以一次能出去的期望为 n/k,平均一次出去的时间为(n次总的时间/n),所以 出迷宫所花费的时间的期望 = 一次能出去的期望 * 平均一次能出去的时间; 

代码:

#include
#include
#include
using namespace std;
#include

int a[110];

int gcd(int a,int b)
{
	return (b==0)?a:gcd(b,a%b);
}
int main()
{
	 int n;
	 int i,j,t;
	 scanf("%d",&t);
	 for(int p = 1;p<=t;p++)
	 {
	 	scanf("%d",&n);
	 	int num = 0;
	 	int sum = 0;
	 	for(i = 0;i0)
				num++;
			sum += abs(a[i]);		
	 	}
	 	printf("Case %d: ",p);
	 	if(num==0) printf("inf\n");
	 	else
	 	{
	 		int g = gcd(sum,num);
	 		printf("%d/%d\n",sum/g,num/g);
	 	}
	 }
	 return 0;
} 

你可能感兴趣的:(期望)