4517: [Sdoi2016]排列计数
Time Limit: 60 Sec Memory Limit: 128 MB[ 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≤1000000
Output
输出 T 行,每行一个数,表示求出的序列数
Sample Input
5
1 0
1 1
5 2
100 50
10000 5000
1 0
1 1
5 2
100 50
10000 5000
Sample Output
0
1
20
578028887
60695423
1
20
578028887
60695423
HINT
这道题预处理逆元应该要快一点,毕竟有50W组数据
错排递推式:f[i] = (i-1)*(f[i-1]+f[i-2])
答案就是C(n,m)*f[n-m]
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<map>
#define mod 1000000007
using namespace std;
typedef long long ll;
const int N = 1000000 + 5;
ll T,n,m,fac[N],f[N];
ll inv( ll x ){
ll y = mod-2,ans=1;
while(y){
if(y&1) ans = ans*x%mod;
x = x*x%mod;
y >>= 1;
}
return ans;
}
int main(){
f[0] = 1; f[1] = 0; fac[0] = 1;
for( int i = 2; i <= N; i++ ) f[i] = ((i-1)*(f[i-1]+f[i-2])%mod)%mod;
for( int i = 1; i <= N; i++ ) fac[i] = fac[i-1]*i%mod;
scanf("%d", &T);
while( T-- ){
scanf("%d%d", &n, &m);
printf("%d\n",fac[n]*inv(fac[m])%mod*inv(fac[n-m])%mod*f[n-m]%mod);
}
return 0;
}