博客
关于我
lightoj1027——经典期望问题(设期望求解)
阅读量:654 次
发布时间:2019-03-15

本文共 1821 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要计算从迷宫中走出的预期时间。每次选择一扇门,门的选择概率相等。如果门可以直接走出迷宫,则花费正数分钟;如果门会回到起点,则花费负数分钟(绝对值)。我们需要计算期望时间,并以最简分数形式输出。

方法思路

  • 问题分析:我们需要计算从起点出发的期望时间。每次选择一扇门,门的选择概率相等。我们需要建立方程来求解期望时间。
  • 数学建模:假设当前期望时间为E。每次选择一扇门,有n种可能性。对于正数门,直接走出迷宫;对于负数门,回到起点并重复过程。
  • 方程求解:通过建立方程E = (sum1 + sum2 * E) / n,解得E = (sum1 + sum2) / (n - num2)。
  • 特殊情况处理:如果所有门都回到起点,或者门的数量超过可走出门数,输出无穷大。
  • 解决代码

    #include 
    #include
    #include
    #include
    #include
    #include
    using namespace std;int gcd(int a, int b) { while (b != 0) { int temp = a % b; a = b; b = temp; } return a;}int main() { string line; int T; while (getline(&line, &std::cin, '\n') != NULL && line.empty()) { // Skip empty lines } T = stoi(line); for (int kcase = 1; kcase <= T; ++kcase) { // Skip any leading empty lines while (getline(&line, &std::cin, '\n') != NULL && line.empty()) { continue; } int n = stoi(line); // Read the next line which contains n integers while (getline(&line, &std::cin, '\n') == NULL) { // Handle EOF break; } istringstream iss(line); vector
    x(n); for (int i = 0; i < n; ++i) { x[i] = iss >> int; } int sum1 = 0, sum2 = 0, num2 = 0; for (int xi : x) { if (xi > 0) { sum1 += xi; } else { sum2 += abs(xi); num2++; } } if (sum1 == 0) { cout << "Case " << kcase << ": inf\n"; } else { int denominator = n - num2; if (denominator <= 0) { cout << "Case " << kcase << ": inf\n"; } else { int sum_total = sum1 + sum2; int g = gcd(sum_total, denominator); int numerator = sum_total / g; int denominator_final = denominator / g; cout << "Case " << kcase << ": " << numerator << "/" << denominator_final << endl; } } } return 0;}

    代码解释

  • 输入处理:读取输入,处理多个测试用例,每个测试用例包含n扇门和每扇门的时间。
  • 计算变量:计算可以直接走出的时间总和sum1,回到起点的时间总和sum2,以及回到起点的门数num2。
  • 期望时间计算:根据公式计算期望时间,如果无法走出迷宫,输出无穷大。
  • 分数化简:使用欧几里得算法计算最大公约数,化简分数,输出结果。
  • 这种方法确保了在处理复杂情况时的正确性和效率。

    转载地址:http://qsfmz.baihongyu.com/

    你可能感兴趣的文章
    mysql一个字段为空时使用另一个字段排序
    查看>>
    MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
    查看>>
    MYSQL一直显示正在启动
    查看>>
    MySQL一站到底!华为首发MySQL进阶宝典,基础+优化+源码+架构+实战五飞
    查看>>
    MySQL万字总结!超详细!
    查看>>
    Mysql下载以及安装(新手入门,超详细)
    查看>>
    MySQL不会性能调优?看看这份清华架构师编写的MySQL性能优化手册吧
    查看>>
    MySQL不同字符集及排序规则详解:业务场景下的最佳选
    查看>>
    Mysql不同官方版本对比
    查看>>
    MySQL与Informix数据库中的同义表创建:深入解析与比较
    查看>>
    mysql与mem_细说 MySQL 之 MEM_ROOT
    查看>>
    MySQL与Oracle的数据迁移注意事项,另附转换工具链接
    查看>>
    mysql丢失更新问题
    查看>>
    MySQL两千万数据优化&迁移
    查看>>
    MySql中 delimiter 详解
    查看>>
    MYSQL中 find_in_set() 函数用法详解
    查看>>
    MySQL中auto_increment有什么作用?(IT枫斗者)
    查看>>
    MySQL中B+Tree索引原理
    查看>>
    mysql中cast() 和convert()的用法讲解
    查看>>
    mysql中datetime与timestamp类型有什么区别
    查看>>