[LightOJ 1027] A Dangerous Maze
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 ximinutes, or can take you out of the maze after xi
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)
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扇門,一些會在xi秒後帶你立刻迷宮,一些會讓你回到-xi秒前,選擇每扇門的概率相同,求離開迷宮所需時間的期望.
這是期望數學的入門題.
我們設出去的期望為E,選正數的概率為P1,之後平均花T1的時間出去;選負數的概率是P2,之後平均花T2的時間出去。
則E=P1*T1+P2*(T2+E);
解得:E=(P1T1+P2T2)/ (1-P2)=(P1T1+P2T2)/ P1
我們再設正權和為S1,負權和為S2,正權數為N1,負權數為N2,總數為N,則:
T1*N1/N+T2*N2/N (S1+S2)/N S1+S2
E=-----------------------------=----------------=----------
N1/N N1/N N1
如果N1為0,那永遠走不出去,輸出inf就行了.
問題就解決了.
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int n; 6 int gcd(int x,int y){return y==0?x:gcd(y,x%y);} 7 int main(){ 8 int T; scanf("%d",&T); 9 for (int Ts=1; Ts<=T; Ts++){ 10 scanf("%d",&n); 11 int sum_pos=0,sum_neg=0,num_pos=0,num_neg=0; 12 for (int i=1; i<=n; i++){ 13 int x; scanf("%d",&x); 14 if (x>0) sum_pos+=x,num_pos++; else sum_neg-=x,num_neg++; 15 } 16 printf("Case %d: ",Ts); 17 if (num_pos==0){printf("inf\n"); continue;} 18 int x=sum_pos+sum_neg,y=n-num_neg,K=gcd(x,y); 19 printf("%d/%d\n",x/K,y/K); 20 } 21 return 0; 22 }View Code
[LightOJ 1027] A Dangerous Maze