本文共 1821 字,大约阅读时间需要 6 分钟。
为了解决这个问题,我们需要计算从迷宫中走出的预期时间。每次选择一扇门,门的选择概率相等。如果门可以直接走出迷宫,则花费正数分钟;如果门会回到起点,则花费负数分钟(绝对值)。我们需要计算期望时间,并以最简分数形式输出。
#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;}
这种方法确保了在处理复杂情况时的正确性和效率。
转载地址:http://qsfmz.baihongyu.com/