HDU 2048(错排公式)

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2048

问题分析

n 个人全没有中奖的概率 -> 发生这种情况的所有可能性/情况总数
我们来想一想全部错排该怎么求。
假设前 n 1 个人都完成了错排,那么第 n 个人可以和这 n 1 个人任意一个互换,那么就完成了全部错排,此时方法数为 ( n 1 ) f ( n 1 )
假设前 n 1 一个人未完成错排,但是前 n 2 个人已经完成了全部错排,第 n 1 个人还是自己的位置,所以只要第 n 个人和第 n 1 个人完成互换即可完成 n 个人错排。但是, n 1 个人中那个未完成错排的人可能是这 n 1 个人里的任意一个,所以方法数为 ( n 1 ) f ( n 2 )
所以错排总的方法数为

f ( n ) = ( n 1 ) ( f ( n 1 ) + f ( n 2 ) )

最后所有情况的可能数为 n !

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int N = 7E5;

int main()
{
    double a[21]={0,0,1};
    for(int i = 3; i < 21; ++i){
        a[i] = (i-1)*(a[i-1]+a[i-2]);
    }
    int t;
    cin>>t;
    while(t--)
    {
        long long sum = 1,n;
        cin>>n;
        for(int i = 1; i <= n; ++i)
            sum *=  i;
        printf("%.2f%%\n",a[n]*100/sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/eternally831143/article/details/80908461