博客
关于我
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 优化 or
    查看>>
    mysql 优化器 key_mysql – 选择*和查询优化器
    查看>>
    MySQL 优化:Explain 执行计划详解
    查看>>
    Mysql 会导致锁表的语法
    查看>>
    mysql 使用sql文件恢复数据库
    查看>>
    mysql 修改默认字符集为utf8
    查看>>
    Mysql 共享锁
    查看>>
    MySQL 内核深度优化
    查看>>
    mysql 内连接、自然连接、外连接的区别
    查看>>
    mysql 写入慢优化
    查看>>
    mysql 分组统计SQL语句
    查看>>
    Mysql 分页
    查看>>
    Mysql 分页语句 Limit原理
    查看>>
    MySql 创建函数 Error Code : 1418
    查看>>
    MySQL 创建新用户及授予权限的完整流程
    查看>>
    mysql 创建表,不能包含关键字values 以及 表id自增问题
    查看>>
    mysql 删除日志文件详解
    查看>>
    mysql 判断表字段是否存在,然后修改
    查看>>
    MySQL 到底能不能放到 Docker 里跑?
    查看>>