Description
求有多少种长度为 (n) 的序列 (A) ,满足以下条件:
(1 sim n) 这 (n) 个数在序列中各出现了一次
若第 (i) 个数 (A[i]) 的值为 (i) ,则称 (i) 是稳定的。序列恰好有 (m) 个数是稳定的
满足条件的序列可能很多,序列数对 (10^9+7) 取模。
(Tleq 500000) , (nleq 1000000) , (mleq 1000000)
Solution
需要用到组合数学和错排公式。
(ans=C_n^mcdot D_{n-m})
其中 (D_n=n!left(1-frac{1}{1!}+frac{1}{2!}-frac{1}{3!}+cdots+(-1)^nfrac{1}{n!} ight))
Code
//It is made by Awson on 2018.2.14
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('
'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 1000000;
const int MOD = 1e9+7;
void read(int &x) {
char ch; bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
x *= 1-2*flag;
}
void print(int x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(int x) {if (x < 0) putchar('-'); print(Abs(x)); }
int A[N+5], inv[N+5], D[N+5], n, m, t;
void work() {
inv[0] = inv[1] = A[1] = A[0] = D[0] = 1;
for (int i = 2; i <= N; i++) inv[i] = -1ll*(MOD/i)*inv[MOD%i]%MOD;
for (int i = 2; i <= N; i++) A[i] = 1ll*A[i-1]*i%MOD, inv[i] = 1ll*inv[i]*inv[i-1]%MOD;
for (int i = 1; i <= N; i++)
if (i%2 == 1) D[i] = (D[i-1]-inv[i])%MOD;
else D[i] = (D[i-1]+inv[i])%MOD;
for (int i = 0; i <= N; i++) D[i] = 1ll*D[i]*A[i]%MOD;
read(t);
while (t--) {
read(n), read(m);
if (n < m) puts("0");
else writeln(int((1ll*A[n]*inv[m]%MOD*inv[n-m]%MOD*D[n-m]%MOD+MOD)%MOD));
}
}
int main() {
work(); return 0;
}