今日学习——错排问题

考新郎

Time Limit: 1000 ms Memory Limit: 32768 KiB

Submit Statistic

Problem Description

在一场盛大的集体婚礼中,为了使婚礼进行的丰富一些,司仪临时想出了有一个有意思的节目,叫做"考新郎",具体的操作是这样的:


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

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

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

Input

输入数据的第一行是一个整数C,表示测试实例的个数,然后是C行数据,每行包含两个整数N和M(1 < M <= N <= 20)

Output

对于每个测试实例,请输出一共有多少种发生这种情况的可能,每个实例的输出占一行。

Sample Input

2
2 2
3 2

Sample Output

1
3
#include<stdio.h>
long long  f(int a)
{
    int i ;
    long long sum = 1;
    for(i=1;i<=a;i++)
    {
        sum=sum*i;
    }
    return sum;
}
long long  c(int b, int a)
{
    long long d;
    d=f(a)/(f(b)*f(a-b));
    return d;
}
long long d(int n)
{
    long long b;
    if(n==1)
    b=0;
    else if(n==2)
        b=1;
    else
    {
        b=(n-1)*(d(n-2)+d(n-1));
    }
    return b;

}
int main()
{
    int n , m ;
    int t , e ;
    scanf("%d",&t);
    for(e=0;e<t;e++)
    {
        scanf("%d %d",&n,&m);
        printf("%lld\n",c(m,n)*d(m));
    }
    return 0;
}

错排公式的推导:https://blog.csdn.net/Ber_Bai/article/details/77112975

猜你喜欢

转载自blog.csdn.net/qq_43345339/article/details/85146586