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.
For each test case, output the answer mod 1000000007(10^9 + 7).
2 1 1 3 1Sample 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;
}