BUAA OJ 871 The stupid owls
题目描述
Bamboo recently bought an owl for sending and receiving letters. Every owl will bring a letter to exactly one person, so normally Bamboo’s owl will only bring letters for her.
Although most owls sold in the magical stores are extremely conscientious almost all the time, sometimes they can also make mistakes. For example, on one occasion Bamboo’s owl brought a letter to her roommate Eve, and Eve’s owl brought a letter to Bamboo .The two stupid owls made mistakes at the same time!
What’s worse, if there were n people, each with a stupid owl, so that every one might get a wrong letter . So what the probability of no one getting his or her correct letter?
输入
The input file will contain a list of positive integers n, one per line(0<n<25)。
输出
For each integer n in the input, output the probability(in percentage form) of the n people all receiving a letter that ought to be sent to another one.
Print each output in one line. Please keep two decimals.
解题思路
数论
D
(
n
)
=
(
n
−
1
)
[
D
(
n
−
2
)
+
D
(
n
−
1
)
]
D(n) = (n-1) [D(n-2) + D(n-1)]
D(n)=(n−1)[D(n−2)+D(n−1)]
特殊地,
D
(
1
)
=
0
,
D
(
2
)
=
1
D(1) = 0, D(2) = 1
D(1)=0,D(2)=1.
错排的概率只需再除以总数 n ! n! n!。
代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iomanip>
using namespace std;
long long d[30];
int main() {
int n;
d[2] = 1;
for (int i = 3; i < 25; ++i) {
d[i] = (i - 1) * (d[i - 2] + d[i - 1]);
}
while (~scanf("%d", &n)) {
long long all = 1;
for (int i = n; i > 1; --i) {
all *= i;
}
cout << setiosflags(ios::fixed) << setprecision(2) << 100 * (double) d[n] / all << '\%' << '\n';
}
}
本文介绍了一种通过错排公式解决概率问题的方法,具体为计算当每个人都有一个可能犯错的猫头鹰传递信件时,所有人收到错误信件的概率。使用了数论中的错排公式,并提供了一个C++实现的代码示例。

43万+

被折叠的 条评论
为什么被折叠?



