Generally only need to use a number of combinations, and when n is greater than m MOD may find this:
const ll MOD = 1e9 + 7;
const int MAXN = 1e6;
ll inv[MAXN + 5], fac[MAXN + 5], invfac[MAXN + 5];
void init_C(int n) {
inv[1] = 1;
for(int i = 2; i <= n; i++)
inv[i] = inv[MOD % i] * (MOD - MOD / i) % MOD;
fac[0] = 1, invfac[0] = 1;
for(int i = 1; i <= n; i++) {
fac[i] = fac[i - 1] * i % MOD;
invfac[i] = invfac[i - 1] * inv[i] % MOD;
}
}
inline ll C(ll n, ll m) {
if(n < m)
return 0;
return fac[n] * invfac[n - m] % MOD * invfac[m] % MOD;
}
Derangement, D [i] denotes the i-th number of kinds (different) not all the elements should be in position (ascending / descending uniquely specify a position and the like) can find out by DP, it is easy to copy the template.
const ll MOD = 1e9 + 7;
const int MAXN = 1e6;
//特殊定义D[0]为1
D[0] = 1, D[1] = 0;
for(int i = 2; i <= MAXN; i++) {
if(i & 1) {
D[i] = ((ll)i * D[i - 1] - 1ll) % MOD;
if(D[i] < 0)
D[i] += MOD;
} else
D[i] = ((ll)i * D[i - 1] + 1ll) % MOD;
}