A Dangerous Maze
题意:一个迷宫里面有N个门。每个门要么把你传送出迷宫,要么把你传送到原来的位置且你的记忆也会回到初始的时候。现在给出每个门传送的时间t,若t为正数,说明该门花费时间t可以将你传送出迷宫,若 t 为负数,说明该门花费时间 t 将你传送到原来的位置。选择每个门的概率是相同的,问你出迷宫所花费时间的期望。输出结果写出分数形式,且分子分母互质,若不能出迷宫输出inf。
解题思路:设花费时间 出迷宫的期望为E。
每个选择只有两种情况——设当前门花费时间的绝对值为T
一:选择的门可以直接把你传送出去,期望为1 / N * T。
二:选择的门把你传送到原来的位置,期望为1 / N * T,又回到初始状态,则出去的期望为1 / N * (T + E)。
设所有可以将你传送出去的门的时间值 总和为sum1,所有可以将你传送回去的门的时间值 总和为sum2。设所有可以将你传送出去的门的数目为door1,所有可以将你传送回去的门的数目为door2。
E = 1 / N * (sum1) + 1 / N * (sum2 + door2 * E)。化简得 E = (sum1 + sum2) / (N-door2); 当然若door2等于N,说明不可能出迷宫。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
#include <bitset>
using namespace std;
#define LL long long
const int INF=0x3f3f3f3f;
int gcd(int a, int b)
{
if(a>b) swap(a,b);
while(b%a)
{
int k=b%a;
b=a;
a=k;
}
return a;
}
int a[110];
int main()
{
int t,n;
int cas=1;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
int sum = 0;
int door = 0;
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
if(a[i] > 0)
{
sum += a[i];
door++;
}
else sum-=a[i];
}
printf("Case %d: ", cas++);
if(door == 0) printf("inf\n");
else printf("%d/%d\n", sum / gcd(sum, door), door/ gcd(sum, door));
}
return 0;
}