博客
关于我
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-开启慢查询&所有操作记录日志
    查看>>
    MySQL-数据目录
    查看>>
    MySQL-数据页的结构
    查看>>
    MySQL-架构篇
    查看>>
    MySQL-索引的分类(聚簇索引、二级索引、联合索引)
    查看>>
    Mysql-触发器及创建触发器失败原因
    查看>>
    MySQL-连接
    查看>>
    mysql-递归查询(二)
    查看>>
    MySQL5.1安装
    查看>>
    mysql5.5和5.6版本间的坑
    查看>>
    mysql5.5最简安装教程
    查看>>
    mysql5.6 TIME,DATETIME,TIMESTAMP
    查看>>
    mysql5.6.21重置数据库的root密码
    查看>>
    Mysql5.6主从复制-基于binlog
    查看>>
    MySQL5.6忘记root密码(win平台)
    查看>>
    MySQL5.6的Linux安装shell脚本之二进制安装(一)
    查看>>
    MySQL5.6的zip包安装教程
    查看>>
    mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
    查看>>
    Webpack 基本环境搭建
    查看>>