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

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枚举到n,每次取i(k <= i < n)个出来,对剩下的n-i个进行错排,即C(n, i) * dp[n - i] (dp[n - i]表示对n-i个数进行错排的方案数),然后将它们累加,但是这样做超时了。
考虑到n较大,k较小,可以反过来处理,总的方案数为n!,可以从总的方案数里减去不符合条件的情况,即不变的个数从0枚举到k-1,注意取模后可能总方案数小于最终答案,为了得到最小正整数解我们应该给答案加上一个MOD再取模

code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 1e4+10;
const int MOD = 1000000007;
ll dp[maxn];
ll fac[maxn];
void getdp(){
    dp[1] = 0ll;
    dp[2] = 1ll;
    fac[0] = 1ll;
    fac[1] = 1ll;
    fac[2] = 2ll;
    for(int i = 3; i <= 10000; i++){
        dp[i] = (ll)(i - 1) * (dp[i-1] + dp[i-2]) % MOD;//求错排和阶乘
        fac[i] = (fac[i-1] * i) % MOD;
    }
}
ll q_pow(ll a,ll b){
    ll ans = 1ll;
    while(b){
        if(b & 1)
            ans = ans * a % MOD;
        b >>= 1;
        a = a * a % MOD;
    }
    return ans % MOD;
}
ll C(ll n,ll k){
    if(n < k)
        return 0;
    if(k > n - k){
        k = n - k;
    }
    ll a = 1ll,b = 1ll;
    for(int i = 1; i <= k; i++){
        a = a * (n - i + 1) % MOD;
        b = b * i % MOD;
    }
    return a * q_pow(b,MOD-2) % MOD;//求逆元,组合数取模
}
int main(){
    getdp();
    int T;
    scanf("%d",&T);
    while(T--){
        int n,k;
        scanf("%d%d",&n,&k);
        ll ans = 0ll;
        for(int i = 0; i < k; i++){
            ans = (ans + (C((ll)n,(ll)i) * dp[n-i]) % MOD) % MOD;
        }
        printf("%lld\n",(MOD+(fac[n]-ans))%MOD);//注意这里需要加上mod防止变成负数,得到最小正整数解
    }
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值