小红的碾压墙
[题目链接](https://www.nowcoder.com/practice/ec8b42da899046589e40a0950b4cf7f8)
思路
本题是一道概率计算题。场上有 个敌方随从排成一排,小红依次使用两张致命射击,每张随机消灭一个存活的随从。问恰好消灭最左边和最右边的随从的概率。
分析
两次致命射击按顺序结算,总的等可能事件数为 (第一次从
个中选一个,第二次从剩余
个中选一个)。
要恰好消灭最左和最右两个随从,有两种有利情形:
- 第一次消灭最左,第二次消灭最右。
- 第一次消灭最右,第二次消灭最左。
因此概率为:
$$
当 时,
,只有两个随从必然碾压墙,符合预期。
当 时,
,与样例一致。
做法
- 读入整数
。
- 若
,直接输出
。
- 否则输出
,保留 10 位小数。
复杂度分析
- 时间复杂度:
,仅需一次除法运算。
- 空间复杂度:
,只使用常数个变量。
代码
#include <cstdio>
using namespace std;
int main() {
int n;
scanf("%d", &n);
if (n <= 2) {
printf("1.0000000000\n");
} else {
double ans = 2.0 / ((long long)n * (n - 1));
printf("%.10f\n", ans);
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n <= 2) {
System.out.printf("%.10f%n", 1.0);
} else {
double ans = 2.0 / ((long) n * (n - 1));
System.out.printf("%.10f%n", ans);
}
}
}
n = int(input())
if n <= 2:
print("1.0000000000")
else:
print(f"{2.0 / (n * (n - 1)):.10f}")
const n = parseInt(require("readline").createInterface({
input: process.stdin
}).on("line", (line) => {
const n = parseInt(line.trim());
if (n <= 2) {
console.log("1.0000000000");
} else {
console.log((2.0 / (n * (n - 1))).toFixed(10));
}
process.exit(0);
}));

京公网安备 11010502036488号