博客
关于我
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 语句操作索引SQL语句
    查看>>
    MySQL 误操作后数据恢复(update,delete忘加where条件)
    查看>>
    MySQL 调优/优化的 101 个建议!
    查看>>
    mysql 转义字符用法_MySql 转义字符的使用说明
    查看>>
    mysql 输入密码秒退
    查看>>
    mysql 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
    查看>>
    mysql 通过查看mysql 配置参数、状态来优化你的mysql
    查看>>
    mysql 里对root及普通用户赋权及更改密码的一些命令
    查看>>
    Mysql 重置自增列的开始序号
    查看>>
    mysql 锁机制 mvcc_Mysql性能优化-事务、锁和MVCC
    查看>>
    MySQL 错误
    查看>>
    mysql 随机数 rand使用
    查看>>
    MySQL 面试题汇总
    查看>>
    MySQL 面试,必须掌握的 8 大核心点
    查看>>
    MySQL 高可用性之keepalived+mysql双主
    查看>>
    MySQL 高性能优化规范建议
    查看>>
    mysql 默认事务隔离级别下锁分析
    查看>>
    Mysql--逻辑架构
    查看>>
    MySql-2019-4-21-复习
    查看>>
    mysql-5.6.17-win32免安装版配置
    查看>>