思路:利用错排公式:F(n) = (n-1)*[F(n-1) + F(n-2)]
错排原理:假设前面n-1个元素全部已经错排好,有F(n-1)种,那么可以将前面n-1个元素中任意一个与第n个元素互换,可以生成n个元素的错排,这样有(n-1)*F(n-1)种方法;
此时,若与第n个元素互换的那个元素,它不放在第n个元素所在的位置,而放在除了它和第n个元素的位置之外的其他n-2个位置中的某一个,那么这样就会有(n-1)*F(n-2),这里是确定好这两个元素的位置,然后让其他n-2个元素错排,有F(n-2)中方法。
故,n个元素对应n个位置的错排方法有:F(n) = (n-1)*[F(n-1) + F(n-2)]
错排公式得证.
n个元素的全排列的种数为n!
故答案的公式为: (F(n)/n! ) * 100%
代码奉上:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
const int MAX_ = 50;
long long a[MAX_][2] = {{1,0},{1,0},{2,1},{6,2}};
void f(){
for(int i = 4; i <= 20; ++i){
a[i][0] = i * a[i-1][0];
a[i][1] = (i-1)*(a[i-1][1] + a[i-2][1]);
}
}
int main()
{
//freopen("f:\\out.txt","w",stdout);
int n, x;
f();
scanf("%d",&n);
while(n--){
scanf("%d",&x);
cout<<setiosflags(ios::fixed);
cout.precision(2);
cout<<a[x][1]*100.0/a[x][0]<<"%"<<endl;
}
return 0;
}