4517: [Sdoi2016]排列计数
Time Limit: 60 Sec Memory Limit: 128 MB
Submit: 1616 Solved: 985
[Submit][Status][Discuss]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≤1000000Output
输出 T 行,每行一个数,表示求出的序列数
Sample Input
5
1 0
1 1
5 2
100 50
10000 5000Sample Output
0
1
20
578028887
60695423HINT
Source
没有任何难度的组合数水题,只要知道错排公式即可。注意$f_1=1$
$$ans=C_n^m*f_{n-m} \quad f_n=(n-1)(f_{n-1}+f_{n-2})$$
快速幂竟然会写错?
#include<cstdio>
#include<algorithm>
#define rep(i,l,r) for (ll i=(l); i<=(r); i++)
typedef long long ll;
using namespace std; const ll N=,mod=;
ll n,m,T,fin[N+],fac[N+],f[N+]; ll pow(ll a,ll b){
ll res;
for (res=; b; a=(a*a)%mod,b>>=)
if (b & ) res=(res*a)%mod;
return res;
} int main(){
freopen("permutation.in","r",stdin);
freopen("permutation.out","w",stdout);
fac[]=; rep(i,,N) fac[i]=(fac[i-]*i)%mod;
fin[N]=pow(fac[N],mod-);
for (ll i=N-; ~i; i--) fin[i]=(fin[i+]*(i+))%mod;
f[]=; f[]=; f[]=; rep(i,,N) f[i]=((i-)*(f[i-]+f[i-]))%mod;
for (scanf("%lld",&T); T--; )
scanf("%lld%lld",&n,&m),printf("%lld\n",((fac[n]*fin[m]%mod*fin[n-m])%mod*f[n-m])%mod);
return ;
}