A Dangerous Maze(期望问题)

题目链接

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 n space 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

Sample Output

Case 1: 1/1

Case 2: inf

Case 3: 18/1

这道题的大致意思就是你在一个迷宫,这里有n个门,你要出去,必须要推开门出去,这n个门后有1个数a,正数代表可以花费a分钟出去,负数代表可以花费a回来,你选择的几个门的概念是相等,问你出去的概念是多少?
设正数的和为sum1,负数和为sum2.
思路:1).第一次出去的期望是 1 / n * sum1。
2).随后出去的期望是1 / n * sum2 + 1 / n * E
那么整体的E= (sum1+sum2)/( n - door2 )。
代码如下:

#include
#include
#include
#include
using namespace std;
int gcd(int a,int b){
     
    return b==0?a:gcd(b,a%b); 
}
int main(){
     
	int t;
	scanf("%d",&t);
	int cnt=0;
	while(t--){
     
		int n;
		cin>>n;
		int sum1=0;
		int sum2=0;
		int door1=0;
		int door2=0;
		int a;
		for(int i=1;i<=n;i++){
     
			cin>>a;
			if(a<0){
     
				door2++;
				sum2=sum2-a;
			}
			else if(a>0){
     
				door1++;
				sum1=sum1+a;
			}
		}
		printf("Case %d: ",++cnt);
		if(door2==n)cout<<"inf"<<endl;
		else {
     
			int sum=sum1+sum2;
			int door=n-door2;
			cout<<sum/gcd(sum,door)<<"/"<<door/gcd(sum,door)<<endl;
		}
	}
} 

道阻且长
自己选的路 跪着也要走完

你可能感兴趣的:(数学,概率论)