博客
关于我
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/

    你可能感兴趣的文章
    MTD技术介绍
    查看>>
    MySQL
    查看>>
    MySQL
    查看>>
    mysql
    查看>>
    MTK Android 如何获取系统权限
    查看>>
    MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
    查看>>
    MySQL - ERROR 1406
    查看>>
    mysql - 视图
    查看>>
    MySQL - 解读MySQL事务与锁机制
    查看>>
    MTTR、MTBF、MTTF的大白话理解
    查看>>
    mt_rand
    查看>>
    mysql -存储过程
    查看>>
    mysql /*! 50100 ... */ 条件编译
    查看>>
    mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
    查看>>
    mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
    查看>>
    mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
    查看>>
    mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
    查看>>
    MySQL 8.0 恢复孤立文件每表ibd文件
    查看>>
    MySQL 8.0开始Group by不再排序
    查看>>
    mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
    查看>>