不容易系列之(4)——考新郎 (hdu 2049)

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

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

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

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

Input

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

Output

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

Sample Input

2
2 2
3 2

Sample Output

1
3

题解:就是从m个元素中选出n个进行错排,错排推导之前有写过,就不推导了,直接引用,dp[n]=(n-1)*(dp[n-1]+dp[n-2]),注意最后输出时要先除再乘,否则会爆long long的。

代码如下:

#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <ctime>
#define maxn 10007
#define N 107
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define eps 0.00000001
using namespace std;
typedef long long ll;
int main()
{
    long long int dp[31];
    dp[0]=0;
    dp[1]=1;
    dp[2]=1;
    dp[3]=2;
    for(int i=4; i<=20; i++)
            dp[i]=(i-1)*(dp[i-1]+dp[i-2]);
    int t;
    cin>>t;
    while(t--)
    {
        int m,n;
        long long int s1=1,s2=1,s3=1;
        cin>>m>>n;
        for(int i=1;i<=m;i++)
            s1*=i;
        for(int i=1;i<=n;i++)
            s2*=i;
        for(int i=1;i<=m-n;i++)
            s3*=i;
        cout<<s1/s2/s3*dp[n]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/baiyi_destroyer/article/details/81099822