E - 不容易系列之(4)――考新郎 错排数公式

国庆期间,省城HZ刚刚举行了一场盛大的集体婚礼,为了使婚礼进行的丰富一些,司仪临时想出了有一个有意思的节目,叫做"考新郎",具体的操作是这样的: 
 

首先,给每位新娘打扮得几乎一模一样,并盖上大大的红盖头随机坐成一排; 
然后,让各位新郎寻找自己的新娘.每人只准找一个,并且不允许多人找一个. 
最后,揭开盖头,如果找错了对象就要当众跪搓衣板... 

看来做新郎也不是容易的事情... 

假设一共有N对新婚夫妇,其中有M个新郎找错了新娘,求发生这种情况一共有多少种可能. 

Input输入数据的第一行是一个整数C,表示测试实例的个数,然后是C行数据,每行包含两个整数N和M(1<M<=N<=20)。 
Output对于每个测试实例,请输出一共有多少种发生这种情况的可能,每个实例的输出占一行。 
Sample Input

2
2 2
3 2

Sample Output

1
3

D(n) = (n-1) [D(n-2) + D(n-1)]
排公式的原形为D(n) = n! (1/0! - 1/1! + 1/2! - 1/3! - ..... + (-1)^n/n!),当n很大时计算就很不方便。一个供参考的简化后的公式是D(n) = [n!/e+0.5] ,其中e是自然对数的底,[x]为x的整数部分。

#include <iostream>
#include <vector>
#include <algorithm>
#include<string>
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 21
typedef long long LL;
/*
在N对中有M对找错了
错排数公式 Dn = (n-1)*(Dn-1 + Dn-2)
*/
LL D[MAXN],A[MAXN];
void init()
{
    D[1] = 1;D[2] =1;D[3] = 2;
    A[0] = A[1] = 1;A[2] =2;A[3] = 6;
    for(int i=4;i<MAXN;i++)
    {
        A[i] = i*A[i-1];
        D[i] = (i-1)*(D[i-1]+D[i-2]);
    }
}
void solve(LL n,LL m)
{
    LL ans;
    ans = A[n]/A[m]/A[n-m]*D[m];
    //ans = floor(ans*10000+0.5)/100;
    printf("%lld\n",ans);
}
int main()
{
    init();
    int c,n,m;
    scanf("%d",&c);
    while(c--)
    {
        scanf("%d%d",&n,&m);
        solve(n,m);
    }
}

 

posted @ 2017-04-01 16:20  joeylee97  阅读(226)  评论(0编辑  收藏  举报