BZOJ4517:[SDOI2016]排列计数(组合数学,错排公式)

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

Solution

模数写错+忘了判掉$n=m$所以$WA$了两发……

别问我没判是怎么过的样例……头铁没有测……

这个题答案显然是$C(n,m)*d[n-m]$,其中$d[i]$为$i$的错排公式。

Code

 1 #include<iostream>
 2 #include<cstdio>
 3 #define N (2000009)
 4 #define LL long long
 5 #define MOD (1000000007)
 6 using namespace std;
 7 
 8 LL T,n,m,inv[N],fac[N],facinv[N],d[N];
 9 
10 void Init()
11 {
12     inv[1]=fac[0]=facinv[0]=1;
13     for (int i=1; i<=2000000; ++i)
14     {
15         if (i!=1) inv[i]=(MOD-MOD/i)*inv[MOD%i]%MOD;
16         fac[i]=fac[i-1]*i%MOD; facinv[i]=facinv[i-1]*inv[i]%MOD;
17     }
18     d[0]=1; d[1]=0; d[2]=1;
19     for (int i=3; i<=2000000; ++i) d[i]=(d[i-1]+d[i-2])*(i-1)%MOD;
20 }
21 
22 LL C(LL n,LL m)
23 {
24     if (n<m) return 0;
25     return fac[n]*facinv[m]%MOD*facinv[n-m]%MOD;
26 }
27 
28 int main()
29 {
30     Init();
31     scanf("%lld",&T);
32     while (T--)
33     {
34         scanf("%lld%lld",&n,&m);
35         printf("%lld
",C(n,m)*d[n-m]%MOD);
36     }
37 }
原文地址:https://www.cnblogs.com/refun/p/10084201.html