您的位置:首页 > 其它

fzu-Wand

2017-08-24 17:59 363 查看

题目:

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,要你将其进行重新排列,使得这n个物品中至少存在k个物品是在自己原来的位置上的。

题目思路:

错排+排列组合

注意求组合数时要用逆元,这里用的费马小定理。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int mod = 1e9+7;
const int INF = 0x3f3f3f3f;
const int maxn = 12345;
int T,n,m;
ll D[maxn];
ll fac[maxn];
ll ans[maxn];

void Get_D()
{
D[0]=1;
D[1]=0;
D[2]=1;
for(int i=3;i<=10000;i++)
D[i]=(((i-1)%mod)*((D[i-1]+D[i-2])%mod))%mod;
}

void Get_fac()
{
fac[0]=1;
for(int i=1;i<=10000;i++)
fac[i]=(fac[i-1]*i)%mod;
}

ll Pow_q(ll a,ll b)
{
ll ans=1;
while(b)
{
if(b&1)
ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans%mod;
}

ll Get_C(ll a,ll b)
{
ll aa,bb;
bb=fac[b];
aa=(fac[b-a]*fac[a])%mod;
ll aa_ni=Pow_q(aa,mod-2);
return ((bb%mod)*(aa_ni%mod))%mod;
}

int main()
{
scanf("%d",&T);
Get_D();
Get_fac();
while(T--)
{
scanf("%d%d",&n,&m);
ll ans=0;
for(int i=m;i<=n;i++)
{
ll c=Get_C(n-i,n)%mod;
ll d=D[n-i]%mod;
ans=(ans+(c*d)%mod)%mod;
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: