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。


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

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#include<stdlib.h>

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;i<n;i++)
	 	{
	 		scanf("%d",&a[i]);
			if(a[i]>0)
				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;
} 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值