LightOj 1027 数学期望

一个迷宫有n扇门,走第i扇门时间为xi,若xi为正,则走出迷宫,若xi为负,则回到原来位置并忘记已走过的门。问走出迷宫的时间期望,若不能走出迷宫输出inf,否则以分数形式输出p/q


【数据范围】
T(100)组数据,1n100,1abs(xi)10000


【分析】
首先对于题目给定的如下样例应该如何推得答案为18/1,

3
3 -6 -9

设定期望为d,即d=13×3+13×(6+d)+13×(9+d)
所以推得13×d=1+2+3,故得最后d=18
同样的当有n个数时,我们假定有a个为正数,b个负数,
就有d=1n×()+1n×(()+b×d),从而an×d=1n×i=1nxi
最后d=i=1nxia,当然,当a=0时那就输出inf


【代码】

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
int res, T, n;
int tot;
int main() {
    scanf("%d", &T);
    while(T--) {
        printf("Case %d: ", ++tot);
        scanf("%d", &n);
        int x = 0;
        res = 0;
        for(int i = 1; i <= n; i++) {
            int a;
            scanf("%d", &a);
            if(a > 0)x++;
            res += abs(a);
        }
        if(x == 0)printf("inf
");
        else {
            int tmp = __gcd(res, x);
            printf("%d/%d
", res / tmp, x / tmp);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/TRDD/p/9813518.html