Description
求有多少种长度为 n 的序列 A,满足以下条件:
1 ~ n 这 n 个数在序列中各出现了一次
若第 i 个数 A[i] 的值为 i,则称 i 是稳定的。序列恰好有 m 个数是稳定的
满足条件的序列可能很多,序列数对 10^9+7 取模。
Input
第一行一个数 T,表示有 T 组数据。
接下来 T 行,每行两个整数 n、m。
T=500000,n≤1000000,m≤1000000
Output
输出 T 行,每行一个数,表示求出的序列数
Sample Input
5
1 0
1 1
5 2
100 50
10000 5000
Sample Output
0
1
20
578028887
60695423
分析
用f[i] 表示错位排列数
我们显然有
ans=Cmn∗f[n−m]
代码
#include <bits/stdc++.h>
#define N 1000005
#define MOD 1000000007
#define ll long long
int f[N],jc[N],ny[N];
int kms(int x,int y)
{
int ans = 1;
while (y)
{
if (y & 1)
ans = (ll) x * ans % MOD;
x = (ll)x * x % MOD;
y >>= 1;
}
return ans;
}
void getCW()
{
f[1] = 0;
f[2] = 1;
for (int i = 3; i <= N - 5; i++)
{
f[i]=((ll)f[i - 1] * (i - 1) % MOD + (ll)f[i - 2] * (i - 1) % MOD) % MOD;
}
f[0] = 1;
}
void getZH()
{
jc[0] = 1;
ny[0] = 1;
for (int i = 1; i <= N - 5; i++)
{
jc[i] = (ll)i * jc[i - 1] % MOD;
ny[i] = kms(jc[i],MOD - 2);
}
}
int main()
{
int T;
scanf("%d",&T);
getCW();
getZH();
while (T--)
{
int n,m;
scanf("%d%d",&n,&m);
printf("%d\n",(ll)jc[n] * ny[m] % MOD * ny[n - m] % MOD * f[n - m] % MOD);
}
}