1. 程式人生 > >[SDOI 2016]排列計數

[SDOI 2016]排列計數

pro i++ turn 排列 mes write dig down ans

Description

題庫鏈接

求有多少種長度為 \(n\) 的序列 \(A\) ,滿足以下條件:

  1. \(1 \sim n\)\(n\) 個數在序列中各出現了一次

  2. 若第 \(i\) 個數 \(A[i]\) 的值為 \(i\) ,則稱 \(i\) 是穩定的。序列恰好有 \(m\) 個數是穩定的

滿足條件的序列可能很多,序列數對 \(10^9+7\) 取模。

\(T\leq 500000\)\(n\leq 1000000\)\(m\leq 1000000\)

Solution

需要用到組合數學和錯排公式。

\(ans=C_n^m\cdot D_{n-m}\)

其中 \(D_n=n!\left(1-\frac{1}{1!}+\frac{1}{2!}-\frac{1}{3!}+\cdots+(-1)^n\frac{1}{n!}\right)\)

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('\n')) #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; }

[SDOI 2016]排列計數