HDU - 2049 不容易系列之(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
问题链接http://acm.hdu.edu.cn/showproblem.php?pid=2049
问题分析:错排问题…把M个找错的当做完全错排来算,还剩下有N-M个人排列组合,于是最后的结果是F(M)*C(N,N-M)…
AC通过的C++语言程序如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
long long a[25];
int conb[25][25];
int C(int n, int m) {
	int i, j;
	for (i = 0; i<n + 1; i++) {
		for (j = 0; j <= i; j++) {
			if (i == j || j == 0)
				conb[i][j] = 1;
			else
				conb[i][j] = conb[i - 1][j] + conb[i - 1][j - 1];
		}
	}
	return conb[n][m];
}
void cp()
{
	a[1] = 0; a[2] = 1;
	for (int i = 3; i < 21; i++)
	{
		a[i] = (i - 1)*(a[i - 1] + a[i - 2]);
	}
}
int main()
{
	cp();
	int k, n, m;
	cin >> k;
	for (int i = 0; i < k; i++)
	{
		cin >> n >> m;
		if (n == m) { cout << a[n] << endl; }
		else { cout << a[m] * C(n, n - m) << endl; }
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44012745/article/details/86643464
今日推荐