【FZU - 2282】 Wand 【错排+费马小定理】

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

公式很明显,就是这个错排不好弄。
错排是有公式的 cp[i]=(i-1)*(cp[i-1]+cp[i-2]) ;
因为组合中 有除法,所以要求逆元,这里我们可以用费马小定理 求逆元。
代码

#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;  
typedef long long LL ;

const int MAXN = 1e4+10;
const LL  mod  = 1e9+7;

LL cp[MAXN]={0,0,1},k[MAXN]={1,1};
void init(){
    for(LL i=3;i<MAXN;i++)  //  错排 
        cp[i]=(i-1)*(cp[i-1]+cp[i-2])%mod; 

    for(LL i=2;i<MAXN;i++) 
        k[i]=k[i-1]*i%mod;
}
LL qp(LL a,LL b,LL c){
    LL base=a%c,s=1;
    while(b){
        if(b&1)  s=s*base%c;
        base=base*base%c;
        b>>=1;
    }
    return s%c;
}
LL getC(LL n,LL m){
    return (( k[n]*qp(k[m]*k[n-m],mod-2,mod))%mod);
}

int main(){
    init();
    int t;scanf("%d",&t);
    while(t--){
        int n,K;scanf("%d%d",&n,&K);
        LL ans=0;
        for(LL i=0;i<K;i++)
            ans=(ans%mod+(getC((LL)n,i)*cp[n-i])%mod)%mod;

         printf("%lld\n",(mod+k[n]%mod-(ans%mod))%mod);// 注意这里要 加上一个mod ,因为可能 是负的 
     } 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值