Wand FZU - 2282(组合数学+错排公式)

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个人拿自己的物品的方案数

思路:选出任意k个人拿自己的物品C(n,k),其余的n-k人均不拿自己的物品,即n-k个人错排

         总的方案数ans=C(n,k)*dp[n-k],遍历k到n-k

       有关组合数求法的一个总结,或许有点用点击打开链接

        

#include<stdio.h>
#include<math.h>
#include<iostream>
#define mod 1000000007
using namespace std;
typedef long long ll;
const int N = 10005;
ll dp[N],fac[N],inv[N];
void init(){//错排公式 
	dp[0]=1;
	dp[1]=0;
	for(int i=2;i<=10000;i++)
	   dp[i]=((i-1)*(dp[i-1]+dp[i-2]))%mod;
}
ll quickM(ll a,ll b){
	ll ans=1,base=a;
	while(b){
		if(b%2) ans=ans*base%mod;
		base=base*base%mod;
		b>>=1;
	}
	return ans;
}
void Init(){
	fac[0]=1;
	for(ll i=1;i<N;i++) fac[i]=(fac[i-1]*i)%mod;
	inv[N-1]=quickM(fac[N-1],mod-2);
	for(ll i=N-2;i>=0;i--) inv[i]=(inv[i+1]*(i+1))%mod;
}
ll C(ll n,ll m){ //求C(n,m) 
	return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
int main(){
	int T;
	scanf("%d",&T);
	init();
	Init();
	while(T--){
		int n,m;
		scanf("%d%d",&n,&m);
	    ll ans=0;
	    for(int i=m;i<=n;i++){
	    	ll sum=C(n,i)*dp[n-i]%mod;
	    	ans=(ans+sum)%mod;
		}
		printf("%lld\n",ans%mod);
	}
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值