FZU - 2282 Wand(排列组合+错排+费马小定理求逆元+快速幂)

142 篇文章 3 订阅
18 篇文章 0 订阅

 

N wizards are attending a meeting. Everyone has his own magic wand. N magic wands was put in a line, numbered from 1 to n(Wand_i owned by wizard_i). After the meeting, n wizards will take a wand one by one in the order of 1 to n. A boring wizard decided to reorder the wands. He is wondering how many ways to reorder the wands so that at least k wizards can get his own wand.

For example, n=3. Initially, the wands are w1 w2 w3. After reordering, the wands become w2 w1 w3. So, wizard 1 will take w2, wizard 2 will take w1, wizard 3 will take w3, only wizard 3 get his own wand.

Input

First line contains an integer T (1 ≤ T ≤ 10), represents there are T test cases.

For each test case: Two number n and k.

1<=n <=10000.1<=k<=100. k<=n.

Output

For each test case, output the answer mod 1000000007(10^9 + 7).

Sample Input

2
1 1
3 1

Sample Output

1
4

 

题意:给出n和k。初始时n个魔杖都在各自的位置,问有多少种排列符合k个魔杖在原来的位置。

解题思路:

 

从n个里面选取k表示这k个在各自的位置,剩下n-k个用错排排一下。因为k较小,所以要求从k到n这个区间的值较大,我们可以求不符合条件的情况,即符合条件的魔杖有0个,有1个,有2个...有k-1个,然后拿总的排列数减去不符合条件的情况即为答案。

另这样做的话用long long 输入可能会超时,与机器有关吧,换个编译器就过了。

 

 

AC代码:
 

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define mod 1000000007
#define ll long long
#define Max 10010

ll a[Max+10],fic[Max+10];

void fff()
{
	//int i;
	a[0] = 1;
	a[1] = 0;
	a[2] = 1;
	fic[1] = 1;
	fic[2] = 2;
	for(ll i = 3;i<Max;i++)
	{
		a[i] = ((i-1)*a[i-1]%mod + (i-1)*a[i-2]%mod)%mod;//错排公式 
		fic[i] = (fic[i-1] * i)%mod; //求阶乘 
	}
		
}

ll p_pow(ll a,ll b)//快速幂 
{
	ll res = 1;
	while(b)
	{
		if(b&1) res = res*a%mod;
		b>>=1;
		a = a*a%mod;
	}
	return res;
}

ll C(ll n,ll m)//求组合数 
{
	if(m>n) return 0;
	if(m==0) return 1;
	if(m>n-m)
		m = n-m;
	ll sum = 1;
	ll sum1 = 1;
	ll k = n;
	for(ll i = 1;i<=m;i++)
	{
		sum = sum*k%mod;
		k--;
		sum1 = sum1 * i %mod;
	}	
	return sum*p_pow(sum1,mod-2)%mod;//费马小定理求逆元后并计算 
}
int main()
{
	ll n,m;
	fff();
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld%lld",&n,&m);
		ll res = 0;
		for(ll i = 0;i<m;i++)
		{
			res = (res + C(n,i)*a[n-i]%mod) %mod;//C(n)(k)*a[n-k] 
		}
		printf("%lld\n",(fic[n] - res + mod)%mod );//总的方案数减去不符合条件的(小于k次的情况) 
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值