
Accept: 84 Submit: 310
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
Sample Output
Source
第八届福建省大学生程序设计竞赛-重现赛(感谢承办方厦门理工学院)
考虑一个有n个元素的排列,
若一个排列中所有的元素都不在自己原来的位置上,那么这样的排列就称为原排列的一个错排。
D[n] = (n-1)(D[n-1]+D[n-2])
//#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
typedef long long ll;
ll dp[10005], fac[10005];
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(ll i = 0; i < k; i++)
{
a = a * (n - i) % mod;
b = b * (i + 1) % mod;
}
return a * qpow(b, mod-2) % mod;
}
void pre()
{
dp[0] = 1;dp[1] = 0;dp[2] = 1;
fac[1] = 1;fac[2] = 2;
for(ll i = 3; i <= 10000; i++)
{
dp[i] = (((i-1) % mod)*((dp[i-2]+dp[i-1]) % mod))% mod;
fac[i] = fac[i-1] * i % mod;
}
}
int main()
{
ll n, k;
pre();
int t;scanf("%d", &t);
while(t--)
{
scanf("%I64d%I64d", &n, &k);
ll ans = 0;
for(int i = 0; i < k; i++)
ans = (ans % mod + (C(n, i) * dp[n-i] % mod)) % mod;
printf("%I64d\n", (mod + (fac[n] % mod) - (ans % mod)) % mod);
}
return 0;
}