组合数学加错排应用

Accept: 83    Submit: 305
Time Limit: 1000 mSec    Memory Limit : 262144 KB

 Problem Description

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

21 13 1

 Sample Output

14

 Source

第八届福建省大学生程序设计竞赛-重现赛(感谢承办方厦门理工学院)

题目链接:http://acm.fzu.edu.cn/problem.php?pid=2282

题目分析:题目意思就是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

#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
#define ll  long long
#define mod 1000000007
ll a[10005],b[10005];
void init()
{

    a[0] = 1;
    a[1] = 0;
    a[2] = 1;
    b[1] = 1;
    b[2] = 2;
    for (int i = 3; i <= 10000; i ++)
    {
        a[i] = (((i - 1) % mod) * ((a[i - 2] + a[i - 1])) % mod) % mod;
        b[i] = ((b[i - 1] % mod) * (i % mod)) % mod;
    }
}
ll qpow(ll a, ll x) ///快速幂
{
    ll res = 1;
    while(x)
    {
        if (x & 1)
        {
            res = (res * a) %mod;
        }
        a = (a * a) % mod;
        x >>= 1;
    }
    return res;
}

ll C(ll n, ll k) ///求组合数模版
{
    if(n < k)
    {
        return 0;
    }

    if(k > n - k)
    {
        k = n - k;
    }

    ll a = 1, b = 1;

    for(int i = 0; i < k; i++)
    {
        a = a * (n - i) % mod;  ///n*(n-1)*(n-2).....*k
        b = b * (i + 1) % mod;  ///1*2*...*k
    }
    return a * qpow(b, mod - 2) % mod;                 ///费小马定理
}
int main()
{
    int n,m;
    int t;
    scanf("%d",&t);
    init();
    while(t--)
    {
        scanf("%d %d",&n,&m);
        ll sum=b[n];
        ll ans=0;
        for(int i=0; i<m; i++)
        {
            ans=( (ans%mod) + ((C(n,i)*a[n-i])%mod) )%mod;
        }
        printf("%lld\n",(mod +(sum%mod)-(ans%mod))%mod);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/najiuzheyangbaacm/article/details/81187941
今日推荐